Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,16 @@ import {
PROVIDER_THREAD_RESUME_FIRST_PROMPT,
PROVIDER_THREAD_RESUME_SECOND_PROMPT,
PROPOSED_PLAN_PROMPT,
READ_ONLY_NEVER_POLICY,
SIMPLE_PROMPT,
SKILL_INVOCATION_CURSOR_MESSAGE,
SUBAGENT_PROMPT,
TODO_LIST_PROMPT,
TOOL_CALL_READ_ONLY_PROMPT,
TURN_INTERRUPT_MID_TOOL_PROMPT,
WORKSPACE_NEVER_POLICY,
} from "../src/orchestration-v2/testkit/fixtures/shared.ts";
import { skillInvocationInput } from "../src/orchestration-v2/testkit/fixtures/skill_invocation/input.ts";
import {
cursorReplayPromptsForWorkspace,
cursorReplayTranscriptCwd,
Expand Down Expand Up @@ -56,24 +60,36 @@ const RECORDINGS = {
prompts: [PROPOSED_PLAN_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/proposed_plan/cursor_transcript.ndjson",
interactionMode: "plan",
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
},
todo_list: {
prompts: [TODO_LIST_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/todo_list/cursor_transcript.ndjson",
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
},
subagent: {
prompts: [SUBAGENT_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/subagent/cursor_transcript.ndjson",
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
},
tool_call_read_only: {
prompts: [TOOL_CALL_READ_ONLY_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/tool_call_read_only/cursor_transcript.ndjson",
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
},
turn_interrupt_mid_tool: {
prompts: [TURN_INTERRUPT_MID_TOOL_PROMPT],
output:
"../src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/cursor_transcript.ndjson",
interruptAfterToolStart: true,
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
},
skill_invocation: {
// The adapter rewrites a discovered `$review` mention to Cursor's native
// `/review` invocation before sending, so the SDK sees the rewritten form.
prompts: [SKILL_INVOCATION_CURSOR_MESSAGE],
output: "../src/orchestration-v2/testkit/fixtures/skill_invocation/cursor_transcript.ndjson",
workspaceFiles: skillInvocationInput().workspaceFiles,
},
} as const;

Expand Down Expand Up @@ -112,8 +128,12 @@ async function prepareWorkspace(scenario: RecordingName): Promise<{
owned: false,
};
}
const recording = RECORDINGS[scenario];
return {
cwd: await makeCheckpointWorkspace(`cursor-agent-sdk-record-${scenario}`),
cwd: await makeCheckpointWorkspace(
`cursor-agent-sdk-record-${scenario}`,
"workspaceFiles" in recording ? recording.workspaceFiles : undefined,
),
owned: true,
};
}
Expand Down Expand Up @@ -189,6 +209,9 @@ try {
...(transcriptCwd === undefined ? {} : { transcriptCwd }),
apiKey,
...("interactionMode" in recording ? { interactionMode: recording.interactionMode } : {}),
...("runtimePolicyOverride" in recording
? { runtimePolicyOverride: recording.runtimePolicyOverride }
: {}),
...("interruptAfterToolStart" in recording
? { interruptAfterToolStart: recording.interruptAfterToolStart }
: {}),
Expand Down
157 changes: 22 additions & 135 deletions apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,128 +39,6 @@ import { isCursorCancellationError, loggedCursorAgentOptions } from "./CursorAge
const decodeCursorSettings = Schema.decodeEffect(CursorSettings);

describe("CursorAdapterV2", () => {
it.effect("sends discovered skills as native slash invocations with runtime instructions", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-skills-" });
const skillDirectory = path.join(workspace, ".cursor", "skills", "review");
yield* fileSystem.makeDirectory(skillDirectory, { recursive: true });
yield* fileSystem.writeFileString(
path.join(skillDirectory, "SKILL.md"),
"---\nname: review\n---\nReview the changes.",
);
const sentMessages: Array<string> = [];
const instanceId = ProviderInstanceId.make("cursor");
const threadId = ThreadId.make("cursor-skills-thread");
const modelSelection = { instanceId, model: "composer-2.5" };
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: workspace,
});
const adapter = makeCursorAdapterV2({
instanceId,
settings: yield* decodeCursorSettings({}),
environment: { HOME: workspace },
fileSystem,
path,
idAllocator: yield* IdAllocatorV2,
serverConfig: yield* ServerConfig.pipe(
Effect.provide(serverConfigLayerTest(workspace, { prefix: "cursor-v2-skills-config-" })),
),
runner: {
assertComplete: Effect.void,
open: () =>
Effect.succeed({
agentId: "native-cursor-skills",
listMessages: Effect.succeed([]),
close: Effect.void,
send: (input) =>
Effect.sync(() => {
sentMessages.push(
typeof input.message === "string" ? input.message : input.message.text,
);
return {
agentId: "native-cursor-skills",
runId: "native-cursor-run",
wait: Effect.succeed({
id: "native-cursor-run",
requestId: "native-request",
status: "finished" as const,
model: { id: "composer-2.5" },
durationMs: 1,
}),
cancel: Effect.void,
};
}),
}),
},
});
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("cursor-skills-session"),
modelSelection,
runtimePolicy,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection,
runtimePolicy,
});
const now = yield* DateTime.now;
yield* runtime.startTurn({
threadId,
providerThread,
modelSelection,
runtimePolicy,
runId: RunId.make("cursor-skills-run"),
runOrdinal: 1,
providerTurnOrdinal: 1,
attemptId: RunAttemptId.make("cursor-skills-attempt"),
rootNodeId: NodeId.make("cursor-skills-root"),
appThread: {
id: threadId,
projectId: ProjectId.make("cursor-skills-project"),
createdBy: "user",
creationSource: "web",
title: "Cursor skills",
providerInstanceId: instanceId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: providerThread.id,
lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
forkedFrom: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
},
message: {
messageId: MessageId.make("cursor-skills-message"),
createdBy: "user",
creationSource: "web",
text: "$review this with $HOME and $missing",
attachments: [],
},
});
yield* runtime.events.pipe(
Stream.filter((event) => event.type === "turn.terminal"),
Stream.runHead,
);
assert.lengthOf(sentMessages, 1);
assert.isTrue(sentMessages[0]!.startsWith("/review this with $HOME and $missing\n\n"));
assert.include(sentMessages[0]!, "Cursor");
assert.include(sentMessages[0]!, "T3 Code");
}).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, idAllocatorLayer))),
);

for (const { status, model } of [
{ status: "finished", model: undefined },
{ status: "cancelled", model: "claude-opus-4-6" },
Expand Down Expand Up @@ -202,20 +80,29 @@ describe("CursorAdapterV2", () => {
close: Effect.void,
send: (input) =>
Effect.gen(function* () {
yield* input.onDelta!({
type: "tool-call-started",
modelCallId: "model-call",
callId: "task-call",
toolCall: {
type: "task",
args: {
description: "Review",
prompt: "Review the code.",
subagentType: { kind: "generalPurpose" },
...(model === undefined ? {} : { model }),
},
// Recorded Cursor task calls (see fixtures/subagent) stream a
// partial-tool-call before tool-call-started with the same args.
// The run then ends without tool-call-completed, which a live
// run cannot produce on demand.
const taskToolCall = {
type: "task" as const,
args: {
description: "Review",
prompt: "Review the code.",
subagentType: { kind: "unspecified" },
...(model === undefined ? {} : { model }),
agentId: "cursor-task-agent",
mode: "unspecified" as const,
},
}).pipe(Effect.orDie);
};
for (const type of ["partial-tool-call", "tool-call-started"] as const) {
yield* input.onDelta!({
type,
modelCallId: "model-call",
callId: "task-call",
toolCall: taskToolCall,
}).pipe(Effect.orDie);
}
return {
agentId: "native-cursor-lifecycle",
runId: "native-cursor-run",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
import type { InteractionUpdate, RunResult } from "@cursor/sdk";
Expand Down Expand Up @@ -44,6 +45,7 @@ import {
makeCursorAgentOptions,
} from "./CursorAdapterV2.ts";
import type { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts";
import type { RuntimePolicyV2Override } from "../RuntimePolicy.ts";

const CursorAgentSdkReplayTranscript = Schema.Struct({
provider: Schema.Literal(CURSOR_PROVIDER),
Expand Down Expand Up @@ -620,6 +622,16 @@ export function makeCursorProviderAdapterRegistryReplayLayer(
ServerConfig,
makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie),
).pipe(Layer.provide(NodeServices.layer));
// Skill discovery also scans user roots under HOME; an empty HOME keeps
// replays from picking up the host's own skills.
const hostEnvironmentLayer = Layer.effect(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This layer acquires a scoped temporary directory, so it should use the scoped layer constructor to keep the directory alive for the layer's lifetime and run its finalizer when the layer scope closes.

Suggested change
const hostEnvironmentLayer = Layer.effect(
const hostEnvironmentLayer = Layer.scoped(

Posted via Macroscope — Effect Service Conventions

HostProcessEnvironment,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-replay-home-" });
return { HOME: home };
}).pipe(Effect.orDie),
).pipe(Layer.provide(NodeServices.layer));
return makeProviderAdapterRegistryDriverLayer({
drivers: [CursorAdapterV2Driver],
configMap: {
Expand All @@ -632,6 +644,7 @@ export function makeCursorProviderAdapterRegistryReplayLayer(
Layer.mergeAll(
makeCursorAgentSdkReplayLayer(transcript, options),
serverConfigLayer,
hostEnvironmentLayer,
NodeServices.layer,
idAllocatorLayer,
),
Expand Down Expand Up @@ -670,24 +683,35 @@ export const CursorOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarnes
makeCursorProviderAdapterRegistryReplayLayer(transcript),
};

function sanitizeReplayText(
text: string,
replacements: ReadonlyArray<readonly [string, string]>,
): string {
return replacements.reduce(
(current, [from, to]) => (from.length === 0 ? current : current.replaceAll(from, to)),
text,
);
}

function sanitizeReplayValue(
value: unknown,
replacements: ReadonlyArray<readonly [string, string]>,
): unknown {
if (typeof value === "string") {
return replacements.reduce(
(text, [from, to]) => (from.length === 0 ? text : text.replaceAll(from, to)),
value,
);
return sanitizeReplayText(value, replacements);
}
if (Array.isArray(value)) {
return value.map((entry) => sanitizeReplayValue(entry, replacements));
}
if (typeof value !== "object" || value === null) {
return value;
}
// Keys too: grep results are keyed by workspace path.
return Object.fromEntries(
Object.entries(value).map(([key, entry]) => [key, sanitizeReplayValue(entry, replacements)]),
Object.entries(value).map(([key, entry]) => [
sanitizeReplayText(key, replacements),
sanitizeReplayValue(entry, replacements),
]),
);
}

Expand Down Expand Up @@ -733,13 +757,14 @@ async function waitForRecordingSignal(signal: Promise<void>, description: string
function recordingRuntimePolicy(input: {
readonly cwd: string;
readonly interactionMode: "default" | "plan";
readonly override?: Pick<RuntimePolicyV2Override, "approvalPolicy" | "sandboxPolicy">;
}): ProviderAdapterV2RuntimePolicy {
return {
runtimeMode: "full-access",
interactionMode: input.interactionMode,
cwd: input.cwd,
approvalPolicy: "never",
sandboxPolicy: {
approvalPolicy: input.override?.approvalPolicy ?? "never",
sandboxPolicy: input.override?.sandboxPolicy ?? {
type: "dangerFullAccess",
networkAccess: true,
},
Expand All @@ -756,6 +781,11 @@ export async function recordCursorAgentSdkReplayTranscript(input: {
/** Stable fixture cwd used to sanitize runtime-only workspace paths in recorded updates. */
readonly transcriptCwd?: string;
readonly interactionMode?: "default" | "plan";
/** The replay fixture's policy override, so the recorded agent.open frame matches replay. */
readonly runtimePolicyOverride?: Pick<
RuntimePolicyV2Override,
"approvalPolicy" | "sandboxPolicy"
>;
readonly apiKey?: string;
readonly interruptAfterToolStart?: boolean;
readonly interruptAfterRunStartPromptIndex?: number;
Expand Down Expand Up @@ -788,6 +818,7 @@ export async function recordCursorAgentSdkReplayTranscript(input: {
const runtimePolicy = recordingRuntimePolicy({
cwd: input.cwd,
interactionMode,
...(input.runtimePolicyOverride === undefined ? {} : { override: input.runtimePolicyOverride }),
});
const options = makeCursorAgentOptions({
...(input.apiKey === undefined ? {} : { apiKey: input.apiKey }),
Expand Down Expand Up @@ -816,8 +847,11 @@ export async function recordCursorAgentSdkReplayTranscript(input: {
},
});

// Agents sometimes search the workspace's parent too; map it to /tmp so the
// recording host's temp layout stays out of the fixture.
const replacements: ReadonlyArray<readonly [string, string]> = [
[input.cwd, input.transcriptCwd ?? `/tmp/cursor-replay-${input.scenario}`],
[input.cwd.slice(0, input.cwd.lastIndexOf("/")), "/tmp"],
];

try {
Expand Down Expand Up @@ -954,6 +988,11 @@ export async function recordCursorAgentSdkReplayTranscript(input: {
toolStarted.promise,
"Cursor SDK tool-call-started before interrupt",
);
// Cancelling synchronously from the SDK's tool-call-started callback
// leaves an unhandled AbortError inside @cursor/sdk that kills the
// process (reproduced on 1.0.22, 1.0.31, and 1.0.32). Cancelling from a
// later timer was clean in the same probes; 10 ms is that deferral.
await Effect.runPromise(Effect.sleep("10 millis"));
entries.push({
type: "expect_outbound",
label: `run.cancel:${index + 1}`,
Expand Down
Loading
Loading