The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | // @effect-diagnostics nodeBuiltinImport:off -- A loopback fake of Cursor's backend drives the real SDK. |
| 2 | import * as NodeHttp from "node:http"; |
| 3 | |
| 4 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 5 | import { assert, describe, it } from "@effect/vitest"; |
| 6 | import type { InteractionUpdate } from "@cursor/sdk"; |
| 7 | import { toolOutputImages } from "@t3tools/shared/toolOutput"; |
| 8 | import { |
| 9 | CheckpointId, |
| 10 | EnvironmentId, |
| 11 | MessageId, |
| 12 | NodeId, |
| 13 | type OrchestrationV2ProviderTurn, |
| 14 | ProjectId, |
| 15 | ProviderInstanceId, |
| 16 | ProviderSessionId, |
| 17 | RunAttemptId, |
| 18 | RunId, |
| 19 | ThreadId, |
| 20 | } from "@t3tools/contracts"; |
| 21 | import * as Cause from "effect/Cause"; |
| 22 | import * as DateTime from "effect/DateTime"; |
| 23 | import * as Deferred from "effect/Deferred"; |
| 24 | import * as Effect from "effect/Effect"; |
| 25 | import * as Exit from "effect/Exit"; |
| 26 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 27 | import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe"; |
| 28 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 29 | import * as FileSystem from "effect/FileSystem"; |
| 30 | import * as Layer from "effect/Layer"; |
| 31 | import * as Option from "effect/Option"; |
| 32 | import * as Path from "effect/Path"; |
| 33 | import * as Stream from "effect/Stream"; |
| 34 | import { vi } from "vite-plus/test"; |
| 35 | |
| 36 | import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; |
| 37 | import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; |
| 38 | import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 39 | import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; |
| 40 | import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; |
| 41 | import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; |
| 42 | import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; |
| 43 | import { |
| 44 | cursorMcpServers, |
| 45 | cursorRuntimeAgentPolicy, |
| 46 | makeCursorAgentOptions, |
| 47 | makeCursorAdapterV2, |
| 48 | nestedToolCallFromEnvelope, |
| 49 | } from "./adapter.ts"; |
| 50 | import * as CursorAgentSdk from "./CursorAgentSdk.ts"; |
| 51 | import * as CursorSdk from "./CursorSdk.ts"; |
| 52 | import { loadCursorSdk } from "./sdk.ts"; |
| 53 | import { cursorWorkspaceMcpServers } from "./workspaceMcpServers.ts"; |
| 54 | |
| 55 | // The SDK reads CURSOR_BACKEND_URL once when it loads, before any test body runs. |
| 56 | const cursorBackendUrl = await vi.hoisted(async () => { |
| 57 | const NodeNet = await import("node:net"); |
| 58 | const probe = NodeNet.createServer(); |
| 59 | await new Promise<void>((resolve) => probe.listen(0, "127.0.0.1", resolve)); |
| 60 | const address = probe.address(); |
| 61 | await new Promise((resolve) => probe.close(resolve)); |
| 62 | const url = `http://127.0.0.1:${typeof address === "object" && address !== null ? address.port : 0}`; |
| 63 | process.env.CURSOR_BACKEND_URL = url; |
| 64 | return url; |
| 65 | }); |
| 66 | |
| 67 | const { Agent, ConfigurationError } = loadCursorSdk(); |
| 68 | |
| 69 | describe("CursorAdapterV2", () => { |
| 70 | it.effect.each([ |
| 71 | { status: "finished", model: undefined, lateModel: undefined }, |
| 72 | { status: "cancelled", model: "claude-opus-4-6", lateModel: undefined }, |
| 73 | { status: "error", model: "custom-fable", lateModel: undefined }, |
| 74 | { status: "finished", model: undefined, lateModel: "gpt-6-sol" }, |
| 75 | { status: "finished", model: "gpt-6-sol", lateModel: null }, |
| 76 | ] as const)( |
| 77 | "projects Cursor tasks and unfinished tools: $status, late model $lateModel", |
| 78 | ({ status, model, lateModel }) => |
| 79 | Effect.gen(function* () { |
| 80 | const fileSystem = yield* FileSystem.FileSystem; |
| 81 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ |
| 82 | prefix: "cursor-v2-lifecycle-", |
| 83 | }); |
| 84 | const instanceId = ProviderInstanceId.make("cursor"); |
| 85 | const threadId = ThreadId.make("cursor-lifecycle-thread"); |
| 86 | const mcpSessions = yield* McpProviderSessions.McpProviderSessions; |
| 87 | yield* mcpSessions.set({ |
| 88 | environmentId: EnvironmentId.make("cursor-lifecycle-environment"), |
| 89 | threadId, |
| 90 | providerSessionId: "cursor-lifecycle-session", |
| 91 | providerInstanceId: instanceId, |
| 92 | endpoint: "http://127.0.0.1:43123/mcp", |
| 93 | authorizationHeader: "Bearer synthetic-cursor-token", |
| 94 | browserToolsAvailable: true, |
| 95 | }); |
| 96 | let sentWithMcpOverride = true; |
| 97 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 98 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 99 | runtimeMode: "full-access", |
| 100 | interactionMode: "default", |
| 101 | cwd: workspace, |
| 102 | }); |
| 103 | const adapter = yield* makeCursorAdapterV2({ |
| 104 | instanceId, |
| 105 | environment: { HOME: workspace }, |
| 106 | }).pipe( |
| 107 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 108 | assertComplete: Effect.void, |
| 109 | open: () => |
| 110 | Effect.succeed({ |
| 111 | agentId: "native-cursor-lifecycle", |
| 112 | listMessages: Effect.succeed([]), |
| 113 | close: Effect.void, |
| 114 | send: (input) => |
| 115 | Effect.gen(function* () { |
| 116 | sentWithMcpOverride = Object.hasOwn(input.options ?? {}, "mcpServers"); |
| 117 | // Recorded tasks stream partial args before start, then end without completion; live runs cannot force this. |
| 118 | const taskToolCall = { |
| 119 | type: "task" as const, |
| 120 | args: { |
| 121 | description: "Review", |
| 122 | prompt: "Review the code.", |
| 123 | subagentType: { kind: "unspecified" }, |
| 124 | ...(model === undefined ? {} : { model }), |
| 125 | agentId: "cursor-task-agent", |
| 126 | mode: "unspecified" as const, |
| 127 | }, |
| 128 | }; |
| 129 | const updates = |
| 130 | lateModel !== undefined |
| 131 | ? (["tool-call-started", "tool-call-completed"] as const) |
| 132 | : (["partial-tool-call", "tool-call-started"] as const); |
| 133 | for (const type of updates) { |
| 134 | yield* input.onDelta!({ |
| 135 | type, |
| 136 | modelCallId: "model-call", |
| 137 | callId: "task-call", |
| 138 | toolCall: { |
| 139 | ...taskToolCall, |
| 140 | args: { |
| 141 | ...taskToolCall.args, |
| 142 | ...(type === "tool-call-completed" |
| 143 | ? { model: lateModel ?? undefined } |
| 144 | : {}), |
| 145 | }, |
| 146 | }, |
| 147 | }); |
| 148 | } |
| 149 | const readUpdates: ReadonlyArray<InteractionUpdate> = [ |
| 150 | { |
| 151 | type: "tool-call-started", |
| 152 | modelCallId: "native-model-call", |
| 153 | callId: "read-secret", |
| 154 | toolCall: { type: "read", args: { path: "secret.txt" } }, |
| 155 | }, |
| 156 | ...(["tool-call-started", "tool-call-completed"] as const).map((type) => ({ |
| 157 | type, |
| 158 | modelCallId: "native-model-call", |
| 159 | callId: "read-open", |
| 160 | toolCall: { |
| 161 | type: "read" as const, |
| 162 | args: { path: "open.txt" }, |
| 163 | ...(type === "tool-call-completed" |
| 164 | ? { |
| 165 | result: { |
| 166 | status: "success" as const, |
| 167 | value: { fileSize: 3, content: "ok\n", totalLines: 1 }, |
| 168 | }, |
| 169 | } |
| 170 | : {}), |
| 171 | }, |
| 172 | })), |
| 173 | { |
| 174 | type: "tool-call-completed", |
| 175 | modelCallId: "native-model-call", |
| 176 | callId: "shell-exit-1", |
| 177 | toolCall: { |
| 178 | type: "shell", |
| 179 | args: { command: "vp test" }, |
| 180 | result: { |
| 181 | status: "success", |
| 182 | value: { |
| 183 | exitCode: 1, |
| 184 | signal: "", |
| 185 | stdout: "", |
| 186 | stderr: "1 failed", |
| 187 | executionTime: 1, |
| 188 | }, |
| 189 | }, |
| 190 | }, |
| 191 | }, |
| 192 | ]; |
| 193 | for (const update of readUpdates) { |
| 194 | yield* input.onDelta!(update); |
| 195 | } |
| 196 | return { |
| 197 | agentId: "native-cursor-lifecycle", |
| 198 | runId: "native-cursor-run", |
| 199 | wait: Effect.succeed({ |
| 200 | id: "native-cursor-run", |
| 201 | requestId: "native-request", |
| 202 | status, |
| 203 | model: { id: "composer-2.5" }, |
| 204 | durationMs: 1, |
| 205 | }), |
| 206 | cancel: Effect.void, |
| 207 | }; |
| 208 | }).pipe(Effect.orDie), |
| 209 | }), |
| 210 | }), |
| 211 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 212 | ); |
| 213 | const runtime = yield* adapter.openSession({ |
| 214 | threadId, |
| 215 | providerSessionId: ProviderSessionId.make("cursor-lifecycle-session"), |
| 216 | modelSelection, |
| 217 | runtimePolicy, |
| 218 | }); |
| 219 | const providerThread = yield* runtime.ensureThread({ |
| 220 | threadId, |
| 221 | modelSelection, |
| 222 | runtimePolicy, |
| 223 | }); |
| 224 | assert.equal(providerThread.nativeMetadata?.cursorStoreCwd, workspace); |
| 225 | const now = yield* DateTime.now; |
| 226 | yield* runtime.startTurn({ |
| 227 | threadId, |
| 228 | providerThread, |
| 229 | modelSelection, |
| 230 | runtimePolicy, |
| 231 | runId: RunId.make("cursor-lifecycle-run"), |
| 232 | runOrdinal: 1, |
| 233 | providerTurnOrdinal: 1, |
| 234 | attemptId: RunAttemptId.make("cursor-lifecycle-attempt"), |
| 235 | rootNodeId: NodeId.make("cursor-lifecycle-root"), |
| 236 | appThread: { |
| 237 | id: threadId, |
| 238 | projectId: ProjectId.make("cursor-lifecycle-project"), |
| 239 | createdBy: "user", |
| 240 | creationSource: "web", |
| 241 | title: "Cursor lifecycle", |
| 242 | providerInstanceId: instanceId, |
| 243 | modelSelection, |
| 244 | runtimeMode: "full-access", |
| 245 | interactionMode: "default", |
| 246 | branch: null, |
| 247 | worktreePath: null, |
| 248 | activeProviderThreadId: providerThread.id, |
| 249 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 250 | forkedFrom: null, |
| 251 | createdAt: now, |
| 252 | updatedAt: now, |
| 253 | archivedAt: null, |
| 254 | settledOverride: null, |
| 255 | settledAt: null, |
| 256 | lastVisitedAt: null, |
| 257 | deletedAt: null, |
| 258 | }, |
| 259 | message: { |
| 260 | messageId: MessageId.make("cursor-lifecycle-message"), |
| 261 | createdBy: "user", |
| 262 | creationSource: "web", |
| 263 | text: "Review the code.", |
| 264 | attachments: [], |
| 265 | }, |
| 266 | }); |
| 267 | const events = yield* runtime.events.pipe( |
| 268 | Stream.takeUntil((event) => event.type === "turn.terminal"), |
| 269 | Stream.runCollect, |
| 270 | ); |
| 271 | assert.isTrue(sentWithMcpOverride); |
| 272 | const rows = events.filter((event) => event.type === "subagent.updated"); |
| 273 | assert.equal(rows[0]?.subagent.status, "running"); |
| 274 | assert.equal(rows[0]?.subagent.model, model ?? null); |
| 275 | assert.equal(rows.at(-1)?.subagent.model, lateModel ?? model ?? null); |
| 276 | assert.equal( |
| 277 | rows.at(-1)?.subagent.status, |
| 278 | lateModel !== undefined |
| 279 | ? "completed" |
| 280 | : status === "finished" |
| 281 | ? "idle" |
| 282 | : status === "cancelled" |
| 283 | ? "cancelled" |
| 284 | : "failed", |
| 285 | ); |
| 286 | assert.isNotNull(rows.at(-1)?.subagent.completedAt); |
| 287 | const unfinished = |
| 288 | status === "finished" ? "interrupted" : status === "error" ? "failed" : "cancelled"; |
| 289 | const finalReads = new Map<string, { status: string; output: unknown; done: boolean }>(); |
| 290 | for (const event of events) { |
| 291 | if ( |
| 292 | event.type === "turn_item.updated" && |
| 293 | event.turnItem.type === "dynamic_tool" && |
| 294 | event.turnItem.toolName === "Read" |
| 295 | ) { |
| 296 | finalReads.set(String(event.turnItem.title), { |
| 297 | status: event.turnItem.status, |
| 298 | output: event.turnItem.output, |
| 299 | done: event.turnItem.completedAt !== null, |
| 300 | }); |
| 301 | } |
| 302 | } |
| 303 | const finalNodes = new Map<string, string>(); |
| 304 | for (const event of events) { |
| 305 | if (event.type === "node.updated" && event.node.kind === "tool_call") { |
| 306 | finalNodes.set(String(event.node.nativeItemRef?.nativeId), event.node.status); |
| 307 | } |
| 308 | } |
| 309 | assert.deepEqual(Object.fromEntries(finalReads), { |
| 310 | "Read secret.txt": { status: unfinished, output: undefined, done: true }, |
| 311 | "Read open.txt": { |
| 312 | status: "completed", |
| 313 | output: { fileSize: 3, content: "ok\n", totalLines: 1 }, |
| 314 | done: true, |
| 315 | }, |
| 316 | }); |
| 317 | assert.deepEqual(Object.fromEntries(finalNodes), { |
| 318 | "read-secret": unfinished, |
| 319 | "read-open": "completed", |
| 320 | "shell-exit-1": "failed", |
| 321 | }); |
| 322 | }).pipe( |
| 323 | Effect.scoped, |
| 324 | Effect.provide( |
| 325 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 326 | ), |
| 327 | ), |
| 328 | ); |
| 329 | |
| 330 | it.effect.each([ |
| 331 | { |
| 332 | reason: "the SDK's detailed plan usage limit code", |
| 333 | wait: Effect.succeed({ |
| 334 | id: "native-cursor-run", |
| 335 | status: "error" as const, |
| 336 | error: { message: "You've hit your usage limit", code: "PRO_USER_USAGE_LIMIT" }, |
| 337 | }), |
| 338 | failure: { class: "usage_limit", message: "You've hit your usage limit" }, |
| 339 | }, |
| 340 | { |
| 341 | reason: "the error Cursor's run ended with", |
| 342 | wait: Effect.succeed({ |
| 343 | id: "native-cursor-run", |
| 344 | requestId: "native-request", |
| 345 | status: "error" as const, |
| 346 | error: { |
| 347 | message: "Model Blocked Please ask your admin to enable access to Claude Fable 5.", |
| 348 | }, |
| 349 | model: { id: "claude-fable-5" }, |
| 350 | durationMs: 1, |
| 351 | }), |
| 352 | failure: { |
| 353 | class: "provider_error", |
| 354 | message: "Model Blocked Please ask your admin to enable access to Claude Fable 5.", |
| 355 | }, |
| 356 | }, |
| 357 | { |
| 358 | reason: "the SDK rate limit that broke the run", |
| 359 | wait: Effect.fail( |
| 360 | new CursorAgentSdk.CursorAgentSdkRunnerError({ |
| 361 | method: "run.wait", |
| 362 | cause: Object.assign(new Error("Too many requests"), { |
| 363 | code: "resource_exhausted", |
| 364 | status: 429, |
| 365 | }), |
| 366 | }), |
| 367 | ), |
| 368 | failure: { |
| 369 | class: "usage_limit", |
| 370 | message: |
| 371 | "Cursor Agent SDK run.wait failed: Too many requests (resource_exhausted, HTTP 429)", |
| 372 | }, |
| 373 | }, |
| 374 | { |
| 375 | reason: "a transport dump sent after earlier commentary", |
| 376 | updates: [ |
| 377 | { type: "text-delta", text: "Checking the build first." }, |
| 378 | { type: "step-completed", stepId: 1, stepDurationMs: 1 }, |
| 379 | { type: "text-delta", text: "Error: RetriableError: WritableIterable is closed" }, |
| 380 | ] satisfies ReadonlyArray<InteractionUpdate>, |
| 381 | wait: Effect.succeed({ |
| 382 | id: "native-cursor-run", |
| 383 | requestId: "native-request", |
| 384 | status: "finished" as const, |
| 385 | model: { id: "claude-fable-5" }, |
| 386 | durationMs: 1, |
| 387 | }), |
| 388 | failure: { |
| 389 | class: "transport_error", |
| 390 | message: "Error: RetriableError: WritableIterable is closed", |
| 391 | }, |
| 392 | }, |
| 393 | { |
| 394 | reason: "no failure when Cursor's resume after the turn ended made no progress", |
| 395 | // Cursor's SDK resumed from an older checkpoint after the answer was |
| 396 | // delivered, regenerated the closing, then gave up on the run. |
| 397 | updates: [ |
| 398 | { type: "text-delta", text: "The answer." }, |
| 399 | { type: "turn-ended" }, |
| 400 | { type: "text-delta", text: "A regenerated closing." }, |
| 401 | { type: "turn-ended" }, |
| 402 | ] satisfies ReadonlyArray<InteractionUpdate>, |
| 403 | wait: Effect.succeed({ |
| 404 | id: "native-cursor-run", |
| 405 | requestId: "native-request", |
| 406 | status: "error" as const, |
| 407 | error: { message: "Agent turn stopped after repeated resume attempts made no progress" }, |
| 408 | model: { id: "claude-fable-5" }, |
| 409 | durationMs: 1, |
| 410 | }), |
| 411 | failure: null, |
| 412 | }, |
| 413 | { |
| 414 | reason: "the error a continuation after the turn ended stopped with", |
| 415 | updates: [ |
| 416 | { type: "text-delta", text: "The answer." }, |
| 417 | { type: "turn-ended" }, |
| 418 | { type: "text-delta", text: "Following up on the stop hook." }, |
| 419 | ] satisfies ReadonlyArray<InteractionUpdate>, |
| 420 | wait: Effect.succeed({ |
| 421 | id: "native-cursor-run", |
| 422 | requestId: "native-request", |
| 423 | status: "error" as const, |
| 424 | error: { message: "Agent turn stopped after repeated resume attempts made no progress" }, |
| 425 | model: { id: "claude-fable-5" }, |
| 426 | durationMs: 1, |
| 427 | }), |
| 428 | failure: { |
| 429 | class: "provider_error", |
| 430 | message: "Agent turn stopped after repeated resume attempts made no progress", |
| 431 | }, |
| 432 | }, |
| 433 | { |
| 434 | reason: "no answer from a resume after the turn ended that made no progress", |
| 435 | updates: [{ type: "turn-ended" }] satisfies ReadonlyArray<InteractionUpdate>, |
| 436 | wait: Effect.succeed({ |
| 437 | id: "native-cursor-run", |
| 438 | requestId: "native-request", |
| 439 | status: "error" as const, |
| 440 | error: { message: "Agent turn stopped after repeated resume attempts made no progress" }, |
| 441 | result: "A regenerated closing.", |
| 442 | model: { id: "claude-fable-5" }, |
| 443 | durationMs: 1, |
| 444 | }), |
| 445 | failure: null, |
| 446 | answers: [], |
| 447 | }, |
| 448 | { |
| 449 | reason: "the token usage Cursor reported", |
| 450 | // Cursor's inputTokens already include cache reads and writes. |
| 451 | updates: [ |
| 452 | { type: "text-delta", text: "Done." }, |
| 453 | { |
| 454 | type: "turn-ended", |
| 455 | usage: { |
| 456 | inputTokens: 31_961, |
| 457 | outputTokens: 181, |
| 458 | cacheReadTokens: 0, |
| 459 | cacheWriteTokens: 31_955, |
| 460 | }, |
| 461 | }, |
| 462 | ] satisfies ReadonlyArray<InteractionUpdate>, |
| 463 | wait: Effect.succeed({ |
| 464 | id: "native-cursor-run", |
| 465 | requestId: "native-request", |
| 466 | status: "finished" as const, |
| 467 | model: { id: "claude-fable-5" }, |
| 468 | durationMs: 1, |
| 469 | }), |
| 470 | failure: null, |
| 471 | usage: { |
| 472 | inputTokens: 31_961, |
| 473 | cachedInputTokens: 0, |
| 474 | cacheCreationTokens: 31_955, |
| 475 | outputTokens: 181, |
| 476 | }, |
| 477 | // The checkpoint holds the context fill; billed input counts every step. |
| 478 | contextFill: { usedTokens: 8_304, maxTokens: 200_000 }, |
| 479 | }, |
| 480 | ])("ends the turn with $reason", ({ updates = [], wait, failure, answers, usage, contextFill }) => |
| 481 | Effect.gen(function* () { |
| 482 | const fileSystem = yield* FileSystem.FileSystem; |
| 483 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ |
| 484 | prefix: "cursor-v2-failure-", |
| 485 | }); |
| 486 | const instanceId = ProviderInstanceId.make("cursor"); |
| 487 | const threadId = ThreadId.make("cursor-failure-thread"); |
| 488 | const modelSelection = { instanceId, model: "claude-fable-5" }; |
| 489 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 490 | runtimeMode: "full-access", |
| 491 | interactionMode: "default", |
| 492 | cwd: workspace, |
| 493 | }); |
| 494 | const adapter = yield* makeCursorAdapterV2({ |
| 495 | instanceId, |
| 496 | environment: { HOME: workspace }, |
| 497 | }).pipe( |
| 498 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 499 | assertComplete: Effect.void, |
| 500 | open: () => |
| 501 | Effect.succeed({ |
| 502 | agentId: "native-cursor-failure", |
| 503 | listMessages: Effect.succeed([]), |
| 504 | readContextUsage: Effect.succeed(contextFill), |
| 505 | close: Effect.void, |
| 506 | send: (input) => |
| 507 | Effect.gen(function* () { |
| 508 | for (const update of updates) { |
| 509 | yield* input.onDelta!(update).pipe(Effect.orDie); |
| 510 | } |
| 511 | return { |
| 512 | agentId: "native-cursor-failure", |
| 513 | runId: "native-cursor-run", |
| 514 | wait, |
| 515 | cancel: Effect.void, |
| 516 | }; |
| 517 | }), |
| 518 | }), |
| 519 | }), |
| 520 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 521 | ); |
| 522 | const runtime = yield* adapter.openSession({ |
| 523 | threadId, |
| 524 | providerSessionId: ProviderSessionId.make("cursor-failure-session"), |
| 525 | modelSelection, |
| 526 | runtimePolicy, |
| 527 | }); |
| 528 | const providerThread = yield* runtime.ensureThread({ |
| 529 | threadId, |
| 530 | modelSelection, |
| 531 | runtimePolicy, |
| 532 | }); |
| 533 | const now = yield* DateTime.now; |
| 534 | yield* runtime.startTurn({ |
| 535 | threadId, |
| 536 | providerThread, |
| 537 | modelSelection, |
| 538 | runtimePolicy, |
| 539 | runId: RunId.make("cursor-failure-run"), |
| 540 | runOrdinal: 1, |
| 541 | providerTurnOrdinal: 1, |
| 542 | attemptId: RunAttemptId.make("cursor-failure-attempt"), |
| 543 | rootNodeId: NodeId.make("cursor-failure-root"), |
| 544 | appThread: { |
| 545 | id: threadId, |
| 546 | projectId: ProjectId.make("cursor-failure-project"), |
| 547 | createdBy: "user", |
| 548 | creationSource: "web", |
| 549 | title: "Cursor failure", |
| 550 | providerInstanceId: instanceId, |
| 551 | modelSelection, |
| 552 | runtimeMode: "full-access", |
| 553 | interactionMode: "default", |
| 554 | branch: null, |
| 555 | worktreePath: null, |
| 556 | activeProviderThreadId: providerThread.id, |
| 557 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 558 | forkedFrom: null, |
| 559 | createdAt: now, |
| 560 | updatedAt: now, |
| 561 | archivedAt: null, |
| 562 | settledOverride: null, |
| 563 | settledAt: null, |
| 564 | lastVisitedAt: null, |
| 565 | deletedAt: null, |
| 566 | }, |
| 567 | message: { |
| 568 | messageId: MessageId.make("cursor-failure-message"), |
| 569 | createdBy: "user", |
| 570 | creationSource: "web", |
| 571 | text: "hi", |
| 572 | attachments: [], |
| 573 | }, |
| 574 | }); |
| 575 | const events = yield* runtime.events.pipe( |
| 576 | Stream.takeUntil((event) => event.type === "turn.terminal"), |
| 577 | Stream.runCollect, |
| 578 | ); |
| 579 | const terminal = events.find((event) => event.type === "turn.terminal"); |
| 580 | assert.equal(terminal?.status, failure === null ? "completed" : "failed"); |
| 581 | assert.equal(terminal?.failure?.class, failure?.class); |
| 582 | assert.equal(terminal?.failure?.message, failure?.message); |
| 583 | if (answers !== undefined) { |
| 584 | assert.deepEqual( |
| 585 | events.flatMap((event) => |
| 586 | event.type === "message.updated" && event.message.role === "assistant" |
| 587 | ? [event.message.text] |
| 588 | : [], |
| 589 | ), |
| 590 | answers, |
| 591 | ); |
| 592 | } |
| 593 | if (usage !== undefined) { |
| 594 | const completedTurn = events.findLast( |
| 595 | (event) => |
| 596 | event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, |
| 597 | ); |
| 598 | assert(completedTurn?.type === "provider_turn.updated"); |
| 599 | assert.deepInclude(completedTurn.providerTurn.turnTokenUsage, usage); |
| 600 | assert.deepInclude(completedTurn.providerTurn.tokenUsage, contextFill); |
| 601 | } |
| 602 | }).pipe( |
| 603 | Effect.scoped, |
| 604 | Effect.provide( |
| 605 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 606 | ), |
| 607 | ), |
| 608 | ); |
| 609 | |
| 610 | it.effect("fails standalone SDK transport diagnostics and compacts with SDK summarize", () => |
| 611 | Effect.gen(function* () { |
| 612 | const fileSystem = yield* FileSystem.FileSystem; |
| 613 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-errors-" }); |
| 614 | const summarizeRequests: Array<boolean> = []; |
| 615 | let sendCalls = 0; |
| 616 | const instanceId = ProviderInstanceId.make("cursor"); |
| 617 | const threadId = ThreadId.make("cursor-transport-error-thread"); |
| 618 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 619 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 620 | runtimeMode: "full-access", |
| 621 | interactionMode: "default", |
| 622 | cwd: workspace, |
| 623 | }); |
| 624 | const adapter = yield* makeCursorAdapterV2({ |
| 625 | instanceId, |
| 626 | environment: { HOME: workspace }, |
| 627 | }).pipe( |
| 628 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 629 | assertComplete: Effect.void, |
| 630 | open: () => |
| 631 | Effect.succeed({ |
| 632 | agentId: "native-cursor-error", |
| 633 | listMessages: Effect.succeed([]), |
| 634 | close: Effect.void, |
| 635 | send: (input) => |
| 636 | Effect.sync(() => { |
| 637 | sendCalls += 1; |
| 638 | summarizeRequests.push(input.summarize === true); |
| 639 | const runId = `native-cursor-run-${sendCalls}`; |
| 640 | return { |
| 641 | agentId: "native-cursor-error", |
| 642 | runId, |
| 643 | wait: Effect.succeed({ |
| 644 | id: runId, |
| 645 | requestId: `native-request-${sendCalls}`, |
| 646 | status: "finished" as const, |
| 647 | model: { id: "composer-2.5" }, |
| 648 | durationMs: 1, |
| 649 | result: |
| 650 | sendCalls === 1 |
| 651 | ? "Error: RetriableError: WritableIterable is closed" |
| 652 | : "Summary of the conversation so far", |
| 653 | }), |
| 654 | cancel: Effect.void, |
| 655 | }; |
| 656 | }), |
| 657 | }), |
| 658 | }), |
| 659 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 660 | ); |
| 661 | const runtime = yield* adapter.openSession({ |
| 662 | threadId, |
| 663 | providerSessionId: ProviderSessionId.make("cursor-error-session"), |
| 664 | modelSelection, |
| 665 | runtimePolicy, |
| 666 | }); |
| 667 | const providerThread = yield* runtime.ensureThread({ |
| 668 | threadId, |
| 669 | modelSelection, |
| 670 | runtimePolicy, |
| 671 | }); |
| 672 | const now = yield* DateTime.now; |
| 673 | const appThread = { |
| 674 | id: threadId, |
| 675 | projectId: ProjectId.make("cursor-error-project"), |
| 676 | createdBy: "user" as const, |
| 677 | creationSource: "web" as const, |
| 678 | title: "Cursor transport failure", |
| 679 | providerInstanceId: instanceId, |
| 680 | modelSelection, |
| 681 | runtimeMode: "full-access" as const, |
| 682 | interactionMode: "default" as const, |
| 683 | branch: null, |
| 684 | worktreePath: null, |
| 685 | activeProviderThreadId: providerThread.id, |
| 686 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 687 | forkedFrom: null, |
| 688 | createdAt: now, |
| 689 | updatedAt: now, |
| 690 | archivedAt: null, |
| 691 | settledOverride: null, |
| 692 | settledAt: null, |
| 693 | lastVisitedAt: null, |
| 694 | deletedAt: null, |
| 695 | }; |
| 696 | yield* runtime.startTurn({ |
| 697 | threadId, |
| 698 | providerThread, |
| 699 | modelSelection, |
| 700 | runtimePolicy, |
| 701 | runId: RunId.make("cursor-error-run"), |
| 702 | runOrdinal: 1, |
| 703 | providerTurnOrdinal: 1, |
| 704 | attemptId: RunAttemptId.make("cursor-error-attempt"), |
| 705 | rootNodeId: NodeId.make("cursor-error-root"), |
| 706 | appThread, |
| 707 | message: { |
| 708 | messageId: MessageId.make("cursor-error-message"), |
| 709 | createdBy: "user", |
| 710 | creationSource: "web", |
| 711 | text: "continue", |
| 712 | attachments: [], |
| 713 | }, |
| 714 | }); |
| 715 | const first = yield* runtime.events.pipe( |
| 716 | Stream.filter((event) => event.type === "turn.terminal"), |
| 717 | Stream.runHead, |
| 718 | ); |
| 719 | assert.isTrue(Option.isSome(first)); |
| 720 | if (Option.isSome(first)) { |
| 721 | assert.equal(first.value.status, "failed"); |
| 722 | assert.equal(first.value.failure?.class, "transport_error"); |
| 723 | } |
| 724 | |
| 725 | assert.isDefined(runtime.compactThread); |
| 726 | yield* runtime.compactThread!({ |
| 727 | threadId, |
| 728 | providerThread, |
| 729 | modelSelection, |
| 730 | runtimePolicy, |
| 731 | runId: RunId.make("cursor-compact-run"), |
| 732 | runOrdinal: 2, |
| 733 | providerTurnOrdinal: 2, |
| 734 | attemptId: RunAttemptId.make("cursor-compact-attempt"), |
| 735 | rootNodeId: NodeId.make("cursor-compact-root"), |
| 736 | appThread, |
| 737 | message: { |
| 738 | messageId: MessageId.make("cursor-compact-message"), |
| 739 | createdBy: "user", |
| 740 | creationSource: "web", |
| 741 | text: "ignored by compactThread", |
| 742 | attachments: [], |
| 743 | }, |
| 744 | }); |
| 745 | const compactionEvents = yield* runtime.events.pipe( |
| 746 | Stream.takeUntil((event) => event.type === "turn.terminal"), |
| 747 | Stream.runCollect, |
| 748 | ); |
| 749 | assert.deepEqual(summarizeRequests, [false, true]); |
| 750 | assert.notInclude(JSON.stringify(compactionEvents), "Summary of the conversation so far"); |
| 751 | }).pipe( |
| 752 | Effect.scoped, |
| 753 | Effect.provide( |
| 754 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 755 | ), |
| 756 | ), |
| 757 | ); |
| 758 | |
| 759 | it.effect("sends T3 instructions to each Cursor conversation that lacks them", () => |
| 760 | Effect.gen(function* () { |
| 761 | const fileSystem = yield* FileSystem.FileSystem; |
| 762 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-device-" }); |
| 763 | const sentMessages: Array<string> = []; |
| 764 | const rewoundAfter: Array<string> = []; |
| 765 | let rewindFails = false; |
| 766 | let nextRunStatus: "finished" | "error" = "finished"; |
| 767 | let nextSummaryCompleted: { readonly failed?: boolean } | undefined; |
| 768 | let createdAgents = 0; |
| 769 | const instanceId = ProviderInstanceId.make("cursor"); |
| 770 | const threadId = ThreadId.make("cursor-device-thread"); |
| 771 | const mcpSessions = yield* McpProviderSessions.McpProviderSessions; |
| 772 | const setDeviceAccess = (device: boolean) => |
| 773 | mcpSessions.set({ |
| 774 | environmentId: EnvironmentId.make("cursor-device-environment"), |
| 775 | threadId, |
| 776 | providerSessionId: "cursor-device-session", |
| 777 | providerInstanceId: instanceId, |
| 778 | endpoint: "http://127.0.0.1:43123/mcp", |
| 779 | authorizationHeader: "Bearer synthetic-cursor-token", |
| 780 | browserToolsAvailable: true, |
| 781 | capabilities: new Set(device ? ["device"] : []), |
| 782 | }); |
| 783 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 784 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 785 | runtimeMode: "full-access", |
| 786 | interactionMode: "default", |
| 787 | cwd: workspace, |
| 788 | }); |
| 789 | const adapter = yield* makeCursorAdapterV2({ |
| 790 | instanceId, |
| 791 | environment: { HOME: workspace }, |
| 792 | }).pipe( |
| 793 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 794 | assertComplete: Effect.void, |
| 795 | open: (openInput) => { |
| 796 | const agentId = openInput.agentId ?? `native-cursor-device-${++createdAgents}`; |
| 797 | return Effect.succeed({ |
| 798 | agentId, |
| 799 | listMessages: Effect.succeed([]), |
| 800 | close: Effect.void, |
| 801 | rewindAfterRun: (runId) => |
| 802 | rewindFails |
| 803 | ? Effect.fail( |
| 804 | new CursorAgentSdk.CursorAgentSdkRunnerError({ |
| 805 | method: "agent.rewind", |
| 806 | cause: "store unavailable", |
| 807 | }), |
| 808 | ) |
| 809 | : Effect.sync(() => void rewoundAfter.push(runId)), |
| 810 | send: (input) => |
| 811 | Effect.sync(() => { |
| 812 | sentMessages.push( |
| 813 | typeof input.message === "string" ? input.message : input.message.text, |
| 814 | ); |
| 815 | const runId = `native-cursor-run-${sentMessages.length}`; |
| 816 | const status = nextRunStatus; |
| 817 | const summaryCompleted = nextSummaryCompleted; |
| 818 | nextRunStatus = "finished"; |
| 819 | nextSummaryCompleted = undefined; |
| 820 | return { |
| 821 | agentId, |
| 822 | runId, |
| 823 | wait: Effect.gen(function* () { |
| 824 | if (summaryCompleted !== undefined) { |
| 825 | yield* input.onDelta!({ |
| 826 | type: "summary-completed", |
| 827 | ...summaryCompleted, |
| 828 | }).pipe(Effect.orDie); |
| 829 | } |
| 830 | return { |
| 831 | id: runId, |
| 832 | requestId: `native-request-${sentMessages.length}`, |
| 833 | status, |
| 834 | ...(status === "error" ? { error: { message: "transient failure" } } : {}), |
| 835 | model: { id: input.options?.model?.id ?? "composer-2.5" }, |
| 836 | durationMs: 1, |
| 837 | }; |
| 838 | }), |
| 839 | cancel: Effect.void, |
| 840 | }; |
| 841 | }), |
| 842 | }); |
| 843 | }, |
| 844 | }), |
| 845 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 846 | ); |
| 847 | const runtime = yield* adapter.openSession({ |
| 848 | threadId, |
| 849 | providerSessionId: ProviderSessionId.make("cursor-device-session"), |
| 850 | modelSelection, |
| 851 | runtimePolicy, |
| 852 | }); |
| 853 | let providerThread = yield* runtime.ensureThread({ |
| 854 | threadId, |
| 855 | modelSelection, |
| 856 | runtimePolicy, |
| 857 | }); |
| 858 | const now = yield* DateTime.now; |
| 859 | const appThread = { |
| 860 | id: threadId, |
| 861 | projectId: ProjectId.make("cursor-device-project"), |
| 862 | createdBy: "user" as const, |
| 863 | creationSource: "web" as const, |
| 864 | title: "Cursor devices", |
| 865 | providerInstanceId: instanceId, |
| 866 | modelSelection, |
| 867 | runtimeMode: "full-access" as const, |
| 868 | interactionMode: "default" as const, |
| 869 | branch: null, |
| 870 | worktreePath: null, |
| 871 | activeProviderThreadId: providerThread.id, |
| 872 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 873 | forkedFrom: null, |
| 874 | createdAt: now, |
| 875 | updatedAt: now, |
| 876 | archivedAt: null, |
| 877 | settledOverride: null, |
| 878 | settledAt: null, |
| 879 | lastVisitedAt: null, |
| 880 | deletedAt: null, |
| 881 | }; |
| 882 | // Starts at run 5: a conversation from before device instructions existed, now resumed. |
| 883 | let runOrdinal = 4; |
| 884 | let lastProviderTurn: OrchestrationV2ProviderTurn | undefined; |
| 885 | const send = Effect.fnUntraced(function* ( |
| 886 | compact = false, |
| 887 | nativeThreadHasTurns?: boolean, |
| 888 | options?: { |
| 889 | readonly model?: string; |
| 890 | readonly status?: "finished" | "error"; |
| 891 | readonly summaryCompleted?: { readonly failed?: boolean }; |
| 892 | }, |
| 893 | ) { |
| 894 | runOrdinal += 1; |
| 895 | nextRunStatus = options?.status ?? "finished"; |
| 896 | nextSummaryCompleted = options?.summaryCompleted; |
| 897 | const turnModelSelection = |
| 898 | options?.model === undefined ? modelSelection : { instanceId, model: options.model }; |
| 899 | const turnInput = { |
| 900 | threadId, |
| 901 | providerThread, |
| 902 | modelSelection: turnModelSelection, |
| 903 | runtimePolicy, |
| 904 | ...(nativeThreadHasTurns === undefined ? {} : { nativeThreadHasTurns }), |
| 905 | runId: RunId.make(`cursor-device-run-${runOrdinal}`), |
| 906 | runOrdinal, |
| 907 | providerTurnOrdinal: runOrdinal, |
| 908 | attemptId: RunAttemptId.make(`cursor-device-attempt-${runOrdinal}`), |
| 909 | rootNodeId: NodeId.make(`cursor-device-root-${runOrdinal}`), |
| 910 | appThread, |
| 911 | message: { |
| 912 | messageId: MessageId.make(`cursor-device-message-${runOrdinal}`), |
| 913 | createdBy: "user" as const, |
| 914 | creationSource: "web" as const, |
| 915 | text: "Open the app.", |
| 916 | attachments: [], |
| 917 | }, |
| 918 | }; |
| 919 | yield* compact ? runtime.compactThread!(turnInput) : runtime.startTurn(turnInput); |
| 920 | const events = yield* runtime.events.pipe( |
| 921 | Stream.takeUntil((event) => event.type === "turn.terminal"), |
| 922 | Stream.runCollect, |
| 923 | ); |
| 924 | const providerTurn = events.findLast((event) => event.type === "provider_turn.updated"); |
| 925 | if (providerTurn?.type === "provider_turn.updated") |
| 926 | lastProviderTurn = providerTurn.providerTurn; |
| 927 | const sent = sentMessages.at(-1)!; |
| 928 | return { |
| 929 | orchestration: sent.includes("## T3 Code orchestration"), |
| 930 | devices: sent.includes("## T3 Code devices"), |
| 931 | runtime: sent.includes("<runtime_info>"), |
| 932 | }; |
| 933 | }); |
| 934 | const told = (orchestration: boolean, devices: boolean, runtime: boolean) => ({ |
| 935 | orchestration, |
| 936 | devices, |
| 937 | runtime, |
| 938 | }); |
| 939 | |
| 940 | yield* setDeviceAccess(true); |
| 941 | assert.deepEqual(yield* send(), told(false, true, true)); |
| 942 | assert.deepEqual(yield* send(), told(false, false, false)); |
| 943 | yield* send(true); |
| 944 | assert.deepEqual( |
| 945 | yield* send(), |
| 946 | told(true, true, true), |
| 947 | "compaction drops what the conversation was told", |
| 948 | ); |
| 949 | yield* setDeviceAccess(false); |
| 950 | assert.deepEqual(yield* send(), told(false, false, false)); |
| 951 | yield* setDeviceAccess(true); |
| 952 | assert.deepEqual(yield* send(), told(false, true, false), "device access turned on later"); |
| 953 | assert.deepEqual(yield* send(), told(false, false, false)); |
| 954 | |
| 955 | assert.deepEqual( |
| 956 | yield* send(false, undefined, { model: "gemini-4-neon", status: "error" }), |
| 957 | told(false, false, true), |
| 958 | "a model change resends runtime instructions", |
| 959 | ); |
| 960 | assert.deepEqual( |
| 961 | yield* send(), |
| 962 | told(false, false, true), |
| 963 | "reverting after a failed model-change run resends runtime instructions", |
| 964 | ); |
| 965 | assert.include(sentMessages.at(-1)!, "as composer-2.5"); |
| 966 | assert.deepEqual( |
| 967 | yield* send(false, undefined, { status: "error" }), |
| 968 | told(false, false, false), |
| 969 | "an unchanged turn omits runtime instructions even when it fails", |
| 970 | ); |
| 971 | assert.deepEqual( |
| 972 | yield* send(), |
| 973 | told(false, false, false), |
| 974 | "a failed unchanged turn keeps delivered runtime instructions", |
| 975 | ); |
| 976 | assert.deepEqual( |
| 977 | yield* send(false, undefined, { model: "gemini-4-neon", status: "error" }), |
| 978 | told(false, false, true), |
| 979 | ); |
| 980 | assert.deepEqual( |
| 981 | yield* send(false, undefined, { model: "gemini-4-neon" }), |
| 982 | told(false, false, true), |
| 983 | "a failed turn does not record runtime instructions as delivered", |
| 984 | ); |
| 985 | assert.include(sentMessages.at(-1)!, "as gemini-4-neon"); |
| 986 | assert.deepEqual( |
| 987 | yield* send(false, undefined, { |
| 988 | model: "gemini-4-neon", |
| 989 | summaryCompleted: { failed: true }, |
| 990 | }), |
| 991 | told(false, false, false), |
| 992 | ); |
| 993 | assert.deepEqual( |
| 994 | yield* send(false, undefined, { |
| 995 | model: "gemini-4-neon", |
| 996 | summaryCompleted: {}, |
| 997 | }), |
| 998 | told(false, false, false), |
| 999 | "a failed auto-compaction keeps delivered instructions", |
| 1000 | ); |
| 1001 | assert.deepEqual( |
| 1002 | yield* send(false, undefined, { model: "gemini-4-neon" }), |
| 1003 | told(true, true, true), |
| 1004 | "auto-compaction drops what the conversation was told", |
| 1005 | ); |
| 1006 | assert.deepEqual( |
| 1007 | yield* send(false, undefined, { model: "gemini-4-neon" }), |
| 1008 | told(false, false, false), |
| 1009 | ); |
| 1010 | |
| 1011 | const keptTurn = lastProviderTurn!; |
| 1012 | yield* send(false, undefined, { model: "gemini-4-neon" }); |
| 1013 | const rollbackToKept = runtime.rollbackThread({ |
| 1014 | providerThread, |
| 1015 | target: { |
| 1016 | type: "provider_turn", |
| 1017 | checkpointId: CheckpointId.make("cursor-device-kept-checkpoint"), |
| 1018 | appRunOrdinal: runOrdinal - 1, |
| 1019 | providerTurn: keptTurn, |
| 1020 | }, |
| 1021 | providerThreadTurns: [keptTurn], |
| 1022 | }); |
| 1023 | rewindFails = true; |
| 1024 | yield* Effect.flip(rollbackToKept); |
| 1025 | rewindFails = false; |
| 1026 | assert.deepEqual( |
| 1027 | yield* send(false, true, { model: "gemini-4-neon" }), |
| 1028 | told(false, false, false), |
| 1029 | "a failed rewind leaves the conversation, and what it was told, unchanged", |
| 1030 | ); |
| 1031 | const rewound = yield* rollbackToKept; |
| 1032 | assert.deepEqual(rewoundAfter, [keptTurn.nativeTurnRef?.nativeId]); |
| 1033 | assert.deepEqual( |
| 1034 | rewound.providerThread.nativeThreadRef, |
| 1035 | providerThread.nativeThreadRef, |
| 1036 | "Cursor rewinds the same agent", |
| 1037 | ); |
| 1038 | assert.deepEqual( |
| 1039 | yield* send(false, true, { model: "gemini-4-neon" }), |
| 1040 | told(true, true, true), |
| 1041 | "the rewound conversation may have dropped instructions a later turn carried", |
| 1042 | ); |
| 1043 | |
| 1044 | const rolledBack = yield* runtime.rollbackThread({ |
| 1045 | providerThread, |
| 1046 | target: { |
| 1047 | type: "thread_start", |
| 1048 | checkpointId: CheckpointId.make("cursor-device-checkpoint"), |
| 1049 | appRunOrdinal: 0, |
| 1050 | }, |
| 1051 | providerThreadTurns: [], |
| 1052 | }); |
| 1053 | assert.strictEqual(rolledBack.providerThread.id, providerThread.id); |
| 1054 | assert.notStrictEqual( |
| 1055 | rolledBack.providerThread.nativeThreadRef?.nativeId, |
| 1056 | providerThread.nativeThreadRef?.nativeId, |
| 1057 | "a rollback to the thread's start has no checkpoint to rewind onto", |
| 1058 | ); |
| 1059 | providerThread = rolledBack.providerThread; |
| 1060 | assert.deepEqual( |
| 1061 | yield* send(false, false, { model: "gemini-4-neon" }), |
| 1062 | told(true, true, true), |
| 1063 | "the fresh agent after a rollback has been told nothing", |
| 1064 | ); |
| 1065 | }).pipe( |
| 1066 | Effect.scoped, |
| 1067 | Effect.provide( |
| 1068 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 1069 | ), |
| 1070 | ), |
| 1071 | ); |
| 1072 | |
| 1073 | it.effect("carries a dropped prompt forward, and resumes a checkpointed one natively", () => |
| 1074 | Effect.gen(function* () { |
| 1075 | const fileSystem = yield* FileSystem.FileSystem; |
| 1076 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-steer-" }); |
| 1077 | const sentMessages: Array<string> = []; |
| 1078 | const resumedRuns: Array<number> = []; |
| 1079 | // Cursor keeps a cancelled run in the conversation only once it saved a checkpoint. |
| 1080 | const checkpointedRuns = new Set<string>(); |
| 1081 | const runEnds: Array<Deferred.Deferred<"finished" | "cancelled">> = []; |
| 1082 | const runDeltas: Array<(update: InteractionUpdate) => Effect.Effect<void>> = []; |
| 1083 | const instanceId = ProviderInstanceId.make("cursor"); |
| 1084 | const threadId = ThreadId.make("cursor-steer-thread"); |
| 1085 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 1086 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 1087 | runtimeMode: "full-access", |
| 1088 | interactionMode: "default", |
| 1089 | cwd: workspace, |
| 1090 | }); |
| 1091 | const adapter = yield* makeCursorAdapterV2({ |
| 1092 | instanceId, |
| 1093 | environment: { HOME: workspace }, |
| 1094 | }).pipe( |
| 1095 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 1096 | assertComplete: Effect.void, |
| 1097 | open: () => |
| 1098 | Effect.succeed({ |
| 1099 | agentId: "native-cursor-steer", |
| 1100 | listMessages: Effect.succeed([]), |
| 1101 | close: Effect.void, |
| 1102 | runCheckpointed: (runId) => |
| 1103 | Effect.succeed( |
| 1104 | runId === undefined |
| 1105 | ? checkpointedRuns.has(`native-cursor-run-${sentMessages.length}`) |
| 1106 | : checkpointedRuns.has(runId), |
| 1107 | ), |
| 1108 | send: (input) => |
| 1109 | Effect.gen(function* () { |
| 1110 | if (input.resume === true) resumedRuns.push(sentMessages.length + 1); |
| 1111 | sentMessages.push( |
| 1112 | typeof input.message === "string" ? input.message : input.message.text, |
| 1113 | ); |
| 1114 | const runId = `native-cursor-run-${sentMessages.length}`; |
| 1115 | const ended = yield* Deferred.make<"finished" | "cancelled">(); |
| 1116 | runEnds.push(ended); |
| 1117 | runDeltas.push((update) => input.onDelta!(update).pipe(Effect.orDie)); |
| 1118 | return { |
| 1119 | agentId: "native-cursor-steer", |
| 1120 | runId, |
| 1121 | // Cursor drops a cancelled run's prompt from the agent's conversation. |
| 1122 | wait: Deferred.await(ended).pipe( |
| 1123 | Effect.map((status) => ({ |
| 1124 | id: runId, |
| 1125 | requestId: `native-request-${sentMessages.length}`, |
| 1126 | status, |
| 1127 | model: { id: "composer-2.5" }, |
| 1128 | durationMs: 1, |
| 1129 | })), |
| 1130 | ), |
| 1131 | cancel: Deferred.succeed(ended, "cancelled"), |
| 1132 | }; |
| 1133 | }), |
| 1134 | }), |
| 1135 | }), |
| 1136 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 1137 | ); |
| 1138 | const runtime = yield* adapter.openSession({ |
| 1139 | threadId, |
| 1140 | providerSessionId: ProviderSessionId.make("cursor-steer-session"), |
| 1141 | modelSelection, |
| 1142 | runtimePolicy, |
| 1143 | }); |
| 1144 | const providerThread = yield* runtime.ensureThread({ |
| 1145 | threadId, |
| 1146 | modelSelection, |
| 1147 | runtimePolicy, |
| 1148 | }); |
| 1149 | const now = yield* DateTime.now; |
| 1150 | const appThread = { |
| 1151 | id: threadId, |
| 1152 | projectId: ProjectId.make("cursor-steer-project"), |
| 1153 | createdBy: "user" as const, |
| 1154 | creationSource: "web" as const, |
| 1155 | title: "Cursor steer", |
| 1156 | providerInstanceId: instanceId, |
| 1157 | modelSelection, |
| 1158 | runtimeMode: "full-access" as const, |
| 1159 | interactionMode: "default" as const, |
| 1160 | branch: null, |
| 1161 | worktreePath: null, |
| 1162 | activeProviderThreadId: providerThread.id, |
| 1163 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 1164 | forkedFrom: null, |
| 1165 | createdAt: now, |
| 1166 | updatedAt: now, |
| 1167 | archivedAt: null, |
| 1168 | settledOverride: null, |
| 1169 | settledAt: null, |
| 1170 | lastVisitedAt: null, |
| 1171 | deletedAt: null, |
| 1172 | }; |
| 1173 | const turnInput = (runOrdinal: number, text: string) => ({ |
| 1174 | threadId, |
| 1175 | providerThread, |
| 1176 | modelSelection, |
| 1177 | runtimePolicy, |
| 1178 | runId: RunId.make(`cursor-steer-run-${runOrdinal}`), |
| 1179 | runOrdinal, |
| 1180 | providerTurnOrdinal: runOrdinal, |
| 1181 | attemptId: RunAttemptId.make(`cursor-steer-attempt-${runOrdinal}`), |
| 1182 | rootNodeId: NodeId.make(`cursor-steer-root-${runOrdinal}`), |
| 1183 | appThread, |
| 1184 | message: { |
| 1185 | messageId: MessageId.make(`cursor-steer-message-${runOrdinal}`), |
| 1186 | createdBy: "user" as const, |
| 1187 | creationSource: "web" as const, |
| 1188 | text, |
| 1189 | attachments: [], |
| 1190 | }, |
| 1191 | }); |
| 1192 | const { message: _message, ...resumeBase } = turnInput(4, ""); |
| 1193 | const resumeInput = (runOrdinal: number) => ({ |
| 1194 | ...resumeBase, |
| 1195 | runId: RunId.make(`cursor-steer-run-${runOrdinal}`), |
| 1196 | runOrdinal, |
| 1197 | providerTurnOrdinal: runOrdinal, |
| 1198 | attemptId: RunAttemptId.make(`cursor-steer-attempt-${runOrdinal}`), |
| 1199 | messageId: MessageId.make(`cursor-steer-message-${runOrdinal}`), |
| 1200 | }); |
| 1201 | const unknown = yield* Effect.flip(runtime.resumeTurn!(resumeInput(1))); |
| 1202 | assert(unknown._tag === "ProviderAdapterTurnStartError"); |
| 1203 | assert.strictEqual( |
| 1204 | (unknown.cause as { readonly _tag?: string })._tag, |
| 1205 | "ProviderResumeUnsupportedError", |
| 1206 | "nothing Cursor checkpointed and no known stopped request: nothing to resume", |
| 1207 | ); |
| 1208 | assert.lengthOf(sentMessages, 0); |
| 1209 | |
| 1210 | const firstPrompt = "Write me a 1000 word story about a dog."; |
| 1211 | const steerText = "No wait, a pig please."; |
| 1212 | |
| 1213 | yield* runtime.startTurn(turnInput(1, firstPrompt)); |
| 1214 | const started = Option.getOrThrow( |
| 1215 | yield* runtime.events.pipe( |
| 1216 | Stream.filter((event) => event.type === "provider_turn.updated"), |
| 1217 | Stream.runHead, |
| 1218 | ), |
| 1219 | ); |
| 1220 | assert(started.type === "provider_turn.updated"); |
| 1221 | yield* runtime.interruptTurn({ providerThread, providerTurnId: started.providerTurn.id }); |
| 1222 | yield* runtime.startTurn(turnInput(2, steerText)); |
| 1223 | |
| 1224 | assert.lengthOf(sentMessages, 2); |
| 1225 | const steered = sentMessages[1]!; |
| 1226 | assert.include(steered, steerText); |
| 1227 | assert.include( |
| 1228 | steered, |
| 1229 | firstPrompt, |
| 1230 | "the interrupted prompt is missing from the run that replaces it", |
| 1231 | ); |
| 1232 | assert.include( |
| 1233 | steered, |
| 1234 | "<runtime_info>", |
| 1235 | "an interrupted first run did not deliver runtime instructions", |
| 1236 | ); |
| 1237 | |
| 1238 | yield* Deferred.succeed(runEnds[1]!, "finished"); |
| 1239 | yield* runtime.events.pipe( |
| 1240 | Stream.filter((event) => event.type === "turn.terminal" && event.status === "completed"), |
| 1241 | Stream.runHead, |
| 1242 | ); |
| 1243 | yield* runtime.startTurn(turnInput(3, "Now a cow.")); |
| 1244 | assert.notInclude(sentMessages[2]!, firstPrompt, "a finished turn carries nothing forward"); |
| 1245 | assert.notInclude( |
| 1246 | sentMessages[2]!, |
| 1247 | "<runtime_info>", |
| 1248 | "a finished turn delivered runtime instructions", |
| 1249 | ); |
| 1250 | |
| 1251 | const interruptRunning = Effect.gen(function* () { |
| 1252 | const running = Option.getOrThrow( |
| 1253 | yield* runtime.events.pipe( |
| 1254 | Stream.filter( |
| 1255 | (event) => |
| 1256 | event.type === "provider_turn.updated" && event.providerTurn.status === "running", |
| 1257 | ), |
| 1258 | Stream.runHead, |
| 1259 | ), |
| 1260 | ); |
| 1261 | assert(running.type === "provider_turn.updated"); |
| 1262 | yield* runtime.interruptTurn({ providerThread, providerTurnId: running.providerTurn.id }); |
| 1263 | }); |
| 1264 | |
| 1265 | // Stopped before Cursor checkpointed it: resume replays the exact request Cursor dropped. |
| 1266 | yield* interruptRunning; |
| 1267 | yield* runtime.resumeTurn!(resumeInput(4)); |
| 1268 | assert.deepEqual(resumedRuns, []); |
| 1269 | assert.strictEqual(sentMessages[3], sentMessages[2]); |
| 1270 | |
| 1271 | // Stopped after a checkpoint: Cursor's own ResumeAction continues it, with no message. |
| 1272 | checkpointedRuns.add("native-cursor-run-4"); |
| 1273 | yield* interruptRunning; |
| 1274 | yield* runtime.resumeTurn!(resumeInput(5)); |
| 1275 | assert.deepEqual(resumedRuns, [5]); |
| 1276 | assert.strictEqual(sentMessages[4], ""); |
| 1277 | |
| 1278 | // The resumed run is stopped before its own checkpoint; the request is still in history. |
| 1279 | yield* interruptRunning; |
| 1280 | yield* runtime.resumeTurn!(resumeInput(6)); |
| 1281 | assert.deepEqual(resumedRuns, [5, 6]); |
| 1282 | |
| 1283 | yield* interruptRunning; |
| 1284 | yield* runtime.startTurn(turnInput(7, "Make it shorter.")); |
| 1285 | assert.notInclude( |
| 1286 | sentMessages[6]!, |
| 1287 | "Now a cow.", |
| 1288 | "a request Cursor checkpointed is not carried forward", |
| 1289 | ); |
| 1290 | |
| 1291 | // A turn that ended without a Stop (a usage limit, say) resumes from Cursor's checkpoint, |
| 1292 | // and stays resumable when that resume is stopped before saving its own. |
| 1293 | checkpointedRuns.add("native-cursor-run-7"); |
| 1294 | yield* Deferred.succeed(runEnds[6]!, "finished"); |
| 1295 | yield* runtime.events.pipe( |
| 1296 | Stream.filter((event) => event.type === "turn.terminal" && event.status === "completed"), |
| 1297 | Stream.runHead, |
| 1298 | ); |
| 1299 | yield* runtime.resumeTurn!(resumeInput(8)); |
| 1300 | yield* interruptRunning; |
| 1301 | yield* runtime.resumeTurn!(resumeInput(9)); |
| 1302 | assert.deepEqual(resumedRuns, [5, 6, 8, 9]); |
| 1303 | |
| 1304 | // Compaction before a checkpointed stop invalidates the interrupted run's runtime instructions, |
| 1305 | // so a subsequent native resume completion must not suppress them on the follow-up turn. |
| 1306 | yield* Deferred.succeed(runEnds[8]!, "finished"); |
| 1307 | yield* runtime.events.pipe( |
| 1308 | Stream.filter((event) => event.type === "turn.terminal" && event.status === "completed"), |
| 1309 | Stream.runHead, |
| 1310 | ); |
| 1311 | const neonSelection = { instanceId, model: "gemini-4-neon" }; |
| 1312 | yield* runtime.startTurn({ |
| 1313 | ...turnInput(10, "Switch model."), |
| 1314 | modelSelection: neonSelection, |
| 1315 | }); |
| 1316 | assert.include(sentMessages[9]!, "as gemini-4-neon"); |
| 1317 | yield* runDeltas[9]!({ type: "summary-completed" }); |
| 1318 | checkpointedRuns.add("native-cursor-run-10"); |
| 1319 | yield* interruptRunning; |
| 1320 | yield* runtime.resumeTurn!({ ...resumeInput(11), modelSelection: neonSelection }); |
| 1321 | assert.strictEqual(sentMessages[10], ""); |
| 1322 | yield* Deferred.succeed(runEnds[10]!, "finished"); |
| 1323 | yield* runtime.events.pipe( |
| 1324 | Stream.filter((event) => event.type === "turn.terminal" && event.status === "completed"), |
| 1325 | Stream.runHead, |
| 1326 | ); |
| 1327 | yield* runtime.startTurn({ |
| 1328 | ...turnInput(12, "After resume."), |
| 1329 | modelSelection: neonSelection, |
| 1330 | }); |
| 1331 | assert.include( |
| 1332 | sentMessages[11]!, |
| 1333 | "as gemini-4-neon", |
| 1334 | "native resume after compaction must not mark invalidated runtime instructions delivered", |
| 1335 | ); |
| 1336 | }).pipe( |
| 1337 | Effect.scoped, |
| 1338 | Effect.provide( |
| 1339 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 1340 | ), |
| 1341 | ), |
| 1342 | ); |
| 1343 | |
| 1344 | it.effect("projects Cursor directory trees and lint diagnostics as file search results", () => |
| 1345 | Effect.gen(function* () { |
| 1346 | const fileSystem = yield* FileSystem.FileSystem; |
| 1347 | const path = yield* Path.Path; |
| 1348 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-search-" }); |
| 1349 | const instanceId = ProviderInstanceId.make("cursor"); |
| 1350 | const threadId = ThreadId.make("cursor-search-thread"); |
| 1351 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 1352 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 1353 | runtimeMode: "full-access", |
| 1354 | interactionMode: "default", |
| 1355 | cwd: workspace, |
| 1356 | }); |
| 1357 | const emptyLsNode = { |
| 1358 | childrenDirs: [], |
| 1359 | childrenFiles: [], |
| 1360 | childrenWereProcessed: true, |
| 1361 | fullSubtreeExtensionCounts: {}, |
| 1362 | numFiles: 0, |
| 1363 | }; |
| 1364 | const updates: ReadonlyArray<InteractionUpdate> = [ |
| 1365 | ...(["tool-call-started", "tool-call-completed"] as const).map((type) => ({ |
| 1366 | type, |
| 1367 | modelCallId: "native-model-call", |
| 1368 | callId: "mcp-weather", |
| 1369 | toolCall: { |
| 1370 | type: "mcp" as const, |
| 1371 | args: { |
| 1372 | providerIdentifier: "weather", |
| 1373 | toolName: "get_weather", |
| 1374 | args: { city: "Berlin" }, |
| 1375 | }, |
| 1376 | ...(type === "tool-call-completed" |
| 1377 | ? { |
| 1378 | result: { |
| 1379 | status: "success" as const, |
| 1380 | value: { |
| 1381 | content: [ |
| 1382 | { text: { text: "Preview complete" } }, |
| 1383 | { image: { data: "iVBORw0KGgo=", mimeType: "image/png" } }, |
| 1384 | ], |
| 1385 | isError: false, |
| 1386 | }, |
| 1387 | }, |
| 1388 | } |
| 1389 | : {}), |
| 1390 | }, |
| 1391 | })), |
| 1392 | { |
| 1393 | type: "tool-call-completed", |
| 1394 | modelCallId: "native-model-call", |
| 1395 | callId: "read-file", |
| 1396 | toolCall: { |
| 1397 | type: "read", |
| 1398 | args: { path: "src/env.ts" }, |
| 1399 | result: { |
| 1400 | status: "success", |
| 1401 | value: { fileSize: 12, content: "---\nfile body", totalLines: 2 }, |
| 1402 | }, |
| 1403 | }, |
| 1404 | }, |
| 1405 | { |
| 1406 | type: "tool-call-completed", |
| 1407 | modelCallId: "native-model-call", |
| 1408 | callId: "ls-nested", |
| 1409 | toolCall: { |
| 1410 | type: "ls", |
| 1411 | args: { path: workspace }, |
| 1412 | result: { |
| 1413 | status: "success", |
| 1414 | value: { |
| 1415 | directoryTreeRoot: { |
| 1416 | ...emptyLsNode, |
| 1417 | absPath: workspace, |
| 1418 | childrenFiles: [{ name: "README.md" }], |
| 1419 | childrenDirs: [ |
| 1420 | { |
| 1421 | ...emptyLsNode, |
| 1422 | absPath: path.join(workspace, "src"), |
| 1423 | childrenFiles: [{ name: "index.ts" }], |
| 1424 | childrenDirs: [ |
| 1425 | { |
| 1426 | ...emptyLsNode, |
| 1427 | absPath: path.join(workspace, "src", "nested"), |
| 1428 | childrenFiles: [{ name: "util.ts" }], |
| 1429 | }, |
| 1430 | ], |
| 1431 | }, |
| 1432 | ], |
| 1433 | }, |
| 1434 | }, |
| 1435 | }, |
| 1436 | }, |
| 1437 | }, |
| 1438 | { |
| 1439 | type: "tool-call-completed", |
| 1440 | modelCallId: "native-model-call", |
| 1441 | callId: "ls-empty", |
| 1442 | toolCall: { |
| 1443 | type: "ls", |
| 1444 | args: { path: path.join(workspace, "empty") }, |
| 1445 | result: { |
| 1446 | status: "success", |
| 1447 | value: { |
| 1448 | directoryTreeRoot: { ...emptyLsNode, absPath: path.join(workspace, "empty") }, |
| 1449 | }, |
| 1450 | }, |
| 1451 | }, |
| 1452 | }, |
| 1453 | { |
| 1454 | type: "tool-call-completed", |
| 1455 | modelCallId: "native-model-call", |
| 1456 | callId: "ls-failed", |
| 1457 | toolCall: { |
| 1458 | type: "ls", |
| 1459 | args: { path: path.join(workspace, "missing") }, |
| 1460 | result: { status: "error", error: "ENOENT" }, |
| 1461 | }, |
| 1462 | }, |
| 1463 | { |
| 1464 | type: "tool-call-completed", |
| 1465 | modelCallId: "native-model-call", |
| 1466 | callId: "grep-failed", |
| 1467 | toolCall: { |
| 1468 | type: "grep", |
| 1469 | args: { pattern: "TODO", path: "src" }, |
| 1470 | result: { status: "error", error: "search failed" }, |
| 1471 | }, |
| 1472 | }, |
| 1473 | { |
| 1474 | type: "tool-call-completed", |
| 1475 | modelCallId: "native-model-call", |
| 1476 | callId: "grep-counts", |
| 1477 | toolCall: { |
| 1478 | type: "grep", |
| 1479 | args: { pattern: "TODO", outputMode: "count" }, |
| 1480 | result: { |
| 1481 | status: "success", |
| 1482 | value: { |
| 1483 | workspaceResults: { |
| 1484 | [workspace]: { |
| 1485 | type: "count", |
| 1486 | output: { |
| 1487 | counts: [ |
| 1488 | { file: "src/a.ts", count: 1 }, |
| 1489 | { file: "src/b.ts", count: 3 }, |
| 1490 | ], |
| 1491 | total: 4, |
| 1492 | }, |
| 1493 | }, |
| 1494 | }, |
| 1495 | }, |
| 1496 | }, |
| 1497 | }, |
| 1498 | }, |
| 1499 | { |
| 1500 | type: "tool-call-completed", |
| 1501 | modelCallId: "native-model-call", |
| 1502 | callId: "glob-failed", |
| 1503 | toolCall: { |
| 1504 | type: "glob", |
| 1505 | args: { globPattern: "*.ts" }, |
| 1506 | result: { status: "error", error: "search failed" }, |
| 1507 | }, |
| 1508 | }, |
| 1509 | { |
| 1510 | type: "tool-call-completed", |
| 1511 | modelCallId: "native-model-call", |
| 1512 | callId: "lints", |
| 1513 | toolCall: { |
| 1514 | type: "readLints", |
| 1515 | args: { paths: ["src/a.ts", "src/b.ts"] }, |
| 1516 | result: { |
| 1517 | status: "success", |
| 1518 | value: { |
| 1519 | totalFiles: 2, |
| 1520 | totalDiagnostics: 3, |
| 1521 | fileDiagnostics: [ |
| 1522 | { |
| 1523 | path: "src/a.ts", |
| 1524 | diagnosticsCount: 2, |
| 1525 | diagnostics: [ |
| 1526 | { |
| 1527 | message: "Unused variable", |
| 1528 | code: "TS6133", |
| 1529 | source: "ts", |
| 1530 | severity: "warning", |
| 1531 | range: { start: { line: 0, character: 4 } }, |
| 1532 | }, |
| 1533 | { |
| 1534 | message: "Cannot find name", |
| 1535 | code: "TS2304", |
| 1536 | source: "ts", |
| 1537 | severity: "error", |
| 1538 | range: { start: { line: 11 } }, |
| 1539 | }, |
| 1540 | ], |
| 1541 | }, |
| 1542 | { |
| 1543 | path: "src/b.ts", |
| 1544 | diagnosticsCount: 1, |
| 1545 | diagnostics: [ |
| 1546 | { |
| 1547 | message: "File-level diagnostic", |
| 1548 | code: "TS0", |
| 1549 | source: "ts", |
| 1550 | severity: "information", |
| 1551 | }, |
| 1552 | ], |
| 1553 | }, |
| 1554 | ], |
| 1555 | }, |
| 1556 | }, |
| 1557 | }, |
| 1558 | }, |
| 1559 | { |
| 1560 | type: "tool-call-completed", |
| 1561 | modelCallId: "native-model-call", |
| 1562 | callId: "lints-empty", |
| 1563 | toolCall: { |
| 1564 | type: "readLints", |
| 1565 | args: { paths: ["src/clean.ts"] }, |
| 1566 | result: { |
| 1567 | status: "success", |
| 1568 | value: { |
| 1569 | totalFiles: 1, |
| 1570 | totalDiagnostics: 0, |
| 1571 | fileDiagnostics: [{ path: "src/clean.ts", diagnosticsCount: 0, diagnostics: [] }], |
| 1572 | }, |
| 1573 | }, |
| 1574 | }, |
| 1575 | }, |
| 1576 | { |
| 1577 | type: "tool-call-completed", |
| 1578 | modelCallId: "native-model-call", |
| 1579 | callId: "lints-failed", |
| 1580 | toolCall: { |
| 1581 | type: "readLints", |
| 1582 | args: { paths: ["src/a.ts"] }, |
| 1583 | result: { status: "error", error: "lint failed" }, |
| 1584 | }, |
| 1585 | }, |
| 1586 | ...["slow-shell", "fast-shell"].map((callId) => ({ |
| 1587 | type: "tool-call-started" as const, |
| 1588 | modelCallId: "native-model-call", |
| 1589 | callId, |
| 1590 | toolCall: { type: "shell" as const, args: { command: callId } }, |
| 1591 | })), |
| 1592 | { |
| 1593 | type: "shell-output-delta", |
| 1594 | event: { case: "stdout", value: { data: "tick 1\n" }, toolCallId: "slow-shell" }, |
| 1595 | }, |
| 1596 | { |
| 1597 | type: "shell-output-delta", |
| 1598 | event: { case: "exit", value: { code: 0 }, toolCallId: "slow-shell" }, |
| 1599 | }, |
| 1600 | ]; |
| 1601 | const adapter = yield* makeCursorAdapterV2({ |
| 1602 | instanceId, |
| 1603 | environment: { HOME: workspace }, |
| 1604 | }).pipe( |
| 1605 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 1606 | assertComplete: Effect.void, |
| 1607 | open: () => |
| 1608 | Effect.succeed({ |
| 1609 | agentId: "native-cursor-search", |
| 1610 | listMessages: Effect.succeed([]), |
| 1611 | close: Effect.void, |
| 1612 | send: (input) => |
| 1613 | Effect.gen(function* () { |
| 1614 | for (const update of updates) { |
| 1615 | if (input.onDelta !== undefined) { |
| 1616 | yield* input.onDelta(update).pipe(Effect.orDie); |
| 1617 | } |
| 1618 | } |
| 1619 | return { |
| 1620 | agentId: "native-cursor-search", |
| 1621 | runId: "native-cursor-run", |
| 1622 | wait: Effect.succeed({ |
| 1623 | id: "native-cursor-run", |
| 1624 | requestId: "native-request", |
| 1625 | status: "finished" as const, |
| 1626 | model: { id: "composer-2.5" }, |
| 1627 | durationMs: 1, |
| 1628 | }), |
| 1629 | cancel: Effect.void, |
| 1630 | }; |
| 1631 | }), |
| 1632 | }), |
| 1633 | }), |
| 1634 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 1635 | ); |
| 1636 | const runtime = yield* adapter.openSession({ |
| 1637 | threadId, |
| 1638 | providerSessionId: ProviderSessionId.make("cursor-search-session"), |
| 1639 | modelSelection, |
| 1640 | runtimePolicy, |
| 1641 | }); |
| 1642 | const providerThread = yield* runtime.ensureThread({ |
| 1643 | threadId, |
| 1644 | modelSelection, |
| 1645 | runtimePolicy, |
| 1646 | }); |
| 1647 | const now = yield* DateTime.now; |
| 1648 | yield* runtime.startTurn({ |
| 1649 | threadId, |
| 1650 | providerThread, |
| 1651 | modelSelection, |
| 1652 | runtimePolicy, |
| 1653 | runId: RunId.make("cursor-search-run"), |
| 1654 | runOrdinal: 1, |
| 1655 | providerTurnOrdinal: 1, |
| 1656 | attemptId: RunAttemptId.make("cursor-search-attempt"), |
| 1657 | rootNodeId: NodeId.make("cursor-search-root"), |
| 1658 | appThread: { |
| 1659 | id: threadId, |
| 1660 | projectId: ProjectId.make("cursor-search-project"), |
| 1661 | createdBy: "user", |
| 1662 | creationSource: "web", |
| 1663 | title: "Cursor search results", |
| 1664 | providerInstanceId: instanceId, |
| 1665 | modelSelection, |
| 1666 | runtimeMode: "full-access", |
| 1667 | interactionMode: "default", |
| 1668 | branch: null, |
| 1669 | worktreePath: null, |
| 1670 | activeProviderThreadId: providerThread.id, |
| 1671 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 1672 | forkedFrom: null, |
| 1673 | createdAt: now, |
| 1674 | updatedAt: now, |
| 1675 | archivedAt: null, |
| 1676 | settledOverride: null, |
| 1677 | settledAt: null, |
| 1678 | lastVisitedAt: null, |
| 1679 | deletedAt: null, |
| 1680 | }, |
| 1681 | message: { |
| 1682 | messageId: MessageId.make("cursor-search-message"), |
| 1683 | createdBy: "user", |
| 1684 | creationSource: "web", |
| 1685 | text: "inspect the workspace", |
| 1686 | attachments: [], |
| 1687 | }, |
| 1688 | }); |
| 1689 | const events = yield* runtime.events.pipe( |
| 1690 | Stream.takeUntil((event) => event.type === "turn.terminal"), |
| 1691 | Stream.runCollect, |
| 1692 | ); |
| 1693 | const mcpItems = events.flatMap((event) => |
| 1694 | event.type === "turn_item.updated" && |
| 1695 | event.turnItem.type === "dynamic_tool" && |
| 1696 | event.turnItem.toolName === "mcp__weather__get_weather" |
| 1697 | ? [event.turnItem] |
| 1698 | : [], |
| 1699 | ); |
| 1700 | assert.deepEqual( |
| 1701 | mcpItems.map((item) => item.status), |
| 1702 | ["running", "completed"], |
| 1703 | ); |
| 1704 | for (const item of mcpItems) { |
| 1705 | assert.equal(item.title, "get weather"); |
| 1706 | assert.deepEqual(item.toolSource, { |
| 1707 | key: "mcp:weather", |
| 1708 | name: "weather", |
| 1709 | kind: "integration", |
| 1710 | }); |
| 1711 | assert.deepEqual(item.input, { city: "Berlin" }); |
| 1712 | } |
| 1713 | const shellItemIds = new Map( |
| 1714 | events.flatMap((event) => |
| 1715 | event.type === "turn_item.updated" && event.turnItem.type === "command_execution" |
| 1716 | ? [[event.turnItem.id, event.turnItem.input] as const] |
| 1717 | : [], |
| 1718 | ), |
| 1719 | ); |
| 1720 | assert.deepEqual( |
| 1721 | events.flatMap((event) => |
| 1722 | event.type === "command_output.delta" |
| 1723 | ? [{ command: shellItemIds.get(event.itemId), chunk: event.chunk }] |
| 1724 | : [], |
| 1725 | ), |
| 1726 | [{ command: "slow-shell", chunk: "tick 1\n" }], |
| 1727 | ); |
| 1728 | assert.deepEqual(toolOutputImages(mcpItems.at(-1)?.output), [ |
| 1729 | { mimeType: "image/png", data: "iVBORw0KGgo=" }, |
| 1730 | ]); |
| 1731 | const fileSearchItems = events.flatMap((event) => |
| 1732 | event.type === "turn_item.updated" && |
| 1733 | event.turnItem.type === "file_search" && |
| 1734 | event.turnItem.status !== "running" |
| 1735 | ? [event.turnItem] |
| 1736 | : [], |
| 1737 | ); |
| 1738 | const readItems = events.flatMap((event) => |
| 1739 | event.type === "turn_item.updated" && |
| 1740 | event.turnItem.type === "dynamic_tool" && |
| 1741 | event.turnItem.toolName === "Read" && |
| 1742 | event.turnItem.status === "completed" |
| 1743 | ? [event.turnItem] |
| 1744 | : [], |
| 1745 | ); |
| 1746 | assert.deepEqual( |
| 1747 | readItems.map((item) => ({ title: item.title, input: item.input })), |
| 1748 | [{ title: "Read src/env.ts", input: { path: "src/env.ts" } }], |
| 1749 | ); |
| 1750 | assert.deepEqual( |
| 1751 | fileSearchItems.map((item) => ({ |
| 1752 | pattern: item.pattern, |
| 1753 | status: item.status, |
| 1754 | results: item.results, |
| 1755 | })), |
| 1756 | [ |
| 1757 | { |
| 1758 | pattern: workspace, |
| 1759 | status: "completed", |
| 1760 | results: [ |
| 1761 | { fileName: path.join(workspace, "README.md") }, |
| 1762 | { fileName: path.join(workspace, "src", "index.ts") }, |
| 1763 | { fileName: path.join(workspace, "src", "nested", "util.ts") }, |
| 1764 | ], |
| 1765 | }, |
| 1766 | { |
| 1767 | pattern: path.join(workspace, "empty"), |
| 1768 | status: "completed", |
| 1769 | results: undefined, |
| 1770 | }, |
| 1771 | { |
| 1772 | pattern: path.join(workspace, "missing"), |
| 1773 | status: "failed", |
| 1774 | results: [{ fileName: path.join(workspace, "missing"), preview: "ENOENT" }], |
| 1775 | }, |
| 1776 | { |
| 1777 | pattern: "TODO", |
| 1778 | status: "failed", |
| 1779 | results: [{ fileName: "src", preview: "search failed" }], |
| 1780 | }, |
| 1781 | { |
| 1782 | pattern: "TODO", |
| 1783 | status: "completed", |
| 1784 | results: [ |
| 1785 | { fileName: "src/a.ts", preview: "1 match" }, |
| 1786 | { fileName: "src/b.ts", preview: "3 matches" }, |
| 1787 | ], |
| 1788 | }, |
| 1789 | { |
| 1790 | pattern: "*.ts", |
| 1791 | status: "failed", |
| 1792 | results: [{ fileName: ".", preview: "search failed" }], |
| 1793 | }, |
| 1794 | { |
| 1795 | pattern: "src/a.ts, src/b.ts", |
| 1796 | status: "completed", |
| 1797 | results: [ |
| 1798 | { fileName: "src/a.ts", line: 1, column: 5, preview: "Unused variable" }, |
| 1799 | { fileName: "src/a.ts", line: 12, preview: "Cannot find name" }, |
| 1800 | { fileName: "src/b.ts", preview: "File-level diagnostic" }, |
| 1801 | ], |
| 1802 | }, |
| 1803 | { |
| 1804 | pattern: "src/clean.ts", |
| 1805 | status: "completed", |
| 1806 | results: undefined, |
| 1807 | }, |
| 1808 | { |
| 1809 | pattern: "src/a.ts", |
| 1810 | status: "failed", |
| 1811 | results: [{ fileName: "src/a.ts", preview: "lint failed" }], |
| 1812 | }, |
| 1813 | ], |
| 1814 | ); |
| 1815 | }).pipe( |
| 1816 | Effect.scoped, |
| 1817 | Effect.provide( |
| 1818 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 1819 | ), |
| 1820 | ), |
| 1821 | ); |
| 1822 | |
| 1823 | it.effect("projects subagent directory trees Cursor serialized without empty lists", () => |
| 1824 | Effect.gen(function* () { |
| 1825 | const fileSystem = yield* FileSystem.FileSystem; |
| 1826 | const path = yield* Path.Path; |
| 1827 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-task-ls-" }); |
| 1828 | const instanceId = ProviderInstanceId.make("cursor"); |
| 1829 | const threadId = ThreadId.make("cursor-task-ls-thread"); |
| 1830 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 1831 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 1832 | runtimeMode: "full-access", |
| 1833 | interactionMode: "default", |
| 1834 | cwd: workspace, |
| 1835 | }); |
| 1836 | // The SDK serializes subagent steps with protobuf toJson(), which omits empty repeated fields. |
| 1837 | const conversationSteps = [ |
| 1838 | { |
| 1839 | toolCall: { |
| 1840 | toolCallId: "tool:ls", |
| 1841 | lsToolCall: { |
| 1842 | args: { path: workspace }, |
| 1843 | result: { |
| 1844 | success: { |
| 1845 | directoryTreeRoot: { |
| 1846 | absPath: workspace, |
| 1847 | childrenWereProcessed: true, |
| 1848 | childrenDirs: [ |
| 1849 | { |
| 1850 | absPath: path.join(workspace, "src"), |
| 1851 | childrenFiles: [{ name: "index.ts" }], |
| 1852 | childrenWereProcessed: true, |
| 1853 | numFiles: 1, |
| 1854 | }, |
| 1855 | ], |
| 1856 | }, |
| 1857 | }, |
| 1858 | }, |
| 1859 | }, |
| 1860 | }, |
| 1861 | }, |
| 1862 | { |
| 1863 | toolCall: { |
| 1864 | toolCallId: "tool:lints", |
| 1865 | readLintsToolCall: { args: {}, result: { success: {} } }, |
| 1866 | }, |
| 1867 | }, |
| 1868 | { |
| 1869 | toolCall: { |
| 1870 | toolCallId: "tool:lints-clean-file", |
| 1871 | readLintsToolCall: { |
| 1872 | args: {}, |
| 1873 | result: { success: { fileDiagnostics: [{ path: "src/clean.ts" }] } }, |
| 1874 | }, |
| 1875 | }, |
| 1876 | }, |
| 1877 | { |
| 1878 | toolCall: { |
| 1879 | toolCallId: "tool:mcp", |
| 1880 | mcpToolCall: { |
| 1881 | args: { providerIdentifier: "docs", toolName: "lookup", args: { query: "ls" } }, |
| 1882 | result: { success: {} }, |
| 1883 | }, |
| 1884 | }, |
| 1885 | }, |
| 1886 | ]; |
| 1887 | const adapter = yield* makeCursorAdapterV2({ |
| 1888 | instanceId, |
| 1889 | environment: { HOME: workspace }, |
| 1890 | }).pipe( |
| 1891 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 1892 | assertComplete: Effect.void, |
| 1893 | open: () => |
| 1894 | Effect.succeed({ |
| 1895 | agentId: "native-cursor-task-ls", |
| 1896 | listMessages: Effect.succeed([]), |
| 1897 | close: Effect.void, |
| 1898 | send: (input) => |
| 1899 | Effect.gen(function* () { |
| 1900 | const args = { |
| 1901 | description: "Explore", |
| 1902 | prompt: "List the workspace.", |
| 1903 | subagentType: { kind: "unspecified" as const }, |
| 1904 | agentId: "cursor-task-agent", |
| 1905 | mode: "unspecified" as const, |
| 1906 | }; |
| 1907 | yield* input.onDelta!({ |
| 1908 | type: "tool-call-started", |
| 1909 | modelCallId: "model-call", |
| 1910 | callId: "task-call", |
| 1911 | toolCall: { type: "task", args }, |
| 1912 | }); |
| 1913 | yield* input.onDelta!({ |
| 1914 | type: "tool-call-completed", |
| 1915 | modelCallId: "model-call", |
| 1916 | callId: "task-call", |
| 1917 | toolCall: { |
| 1918 | type: "task", |
| 1919 | args, |
| 1920 | result: { |
| 1921 | status: "success", |
| 1922 | value: { |
| 1923 | conversationSteps, |
| 1924 | isBackground: false, |
| 1925 | backgroundReason: "unspecified", |
| 1926 | }, |
| 1927 | }, |
| 1928 | }, |
| 1929 | }); |
| 1930 | return { |
| 1931 | agentId: "native-cursor-task-ls", |
| 1932 | runId: "native-cursor-run", |
| 1933 | wait: Effect.succeed({ |
| 1934 | id: "native-cursor-run", |
| 1935 | requestId: "native-request", |
| 1936 | status: "finished" as const, |
| 1937 | model: { id: "composer-2.5" }, |
| 1938 | durationMs: 1, |
| 1939 | }), |
| 1940 | cancel: Effect.void, |
| 1941 | }; |
| 1942 | }).pipe(Effect.orDie), |
| 1943 | }), |
| 1944 | }), |
| 1945 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 1946 | ); |
| 1947 | const runtime = yield* adapter.openSession({ |
| 1948 | threadId, |
| 1949 | providerSessionId: ProviderSessionId.make("cursor-task-ls-session"), |
| 1950 | modelSelection, |
| 1951 | runtimePolicy, |
| 1952 | }); |
| 1953 | const providerThread = yield* runtime.ensureThread({ |
| 1954 | threadId, |
| 1955 | modelSelection, |
| 1956 | runtimePolicy, |
| 1957 | }); |
| 1958 | const now = yield* DateTime.now; |
| 1959 | yield* runtime.startTurn({ |
| 1960 | threadId, |
| 1961 | providerThread, |
| 1962 | modelSelection, |
| 1963 | runtimePolicy, |
| 1964 | runId: RunId.make("cursor-task-ls-run"), |
| 1965 | runOrdinal: 1, |
| 1966 | providerTurnOrdinal: 1, |
| 1967 | attemptId: RunAttemptId.make("cursor-task-ls-attempt"), |
| 1968 | rootNodeId: NodeId.make("cursor-task-ls-root"), |
| 1969 | appThread: { |
| 1970 | id: threadId, |
| 1971 | projectId: ProjectId.make("cursor-task-ls-project"), |
| 1972 | createdBy: "user", |
| 1973 | creationSource: "web", |
| 1974 | title: "Cursor subagent ls", |
| 1975 | providerInstanceId: instanceId, |
| 1976 | modelSelection, |
| 1977 | runtimeMode: "full-access", |
| 1978 | interactionMode: "default", |
| 1979 | branch: null, |
| 1980 | worktreePath: null, |
| 1981 | activeProviderThreadId: providerThread.id, |
| 1982 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 1983 | forkedFrom: null, |
| 1984 | createdAt: now, |
| 1985 | updatedAt: now, |
| 1986 | archivedAt: null, |
| 1987 | settledOverride: null, |
| 1988 | settledAt: null, |
| 1989 | lastVisitedAt: null, |
| 1990 | deletedAt: null, |
| 1991 | }, |
| 1992 | message: { |
| 1993 | messageId: MessageId.make("cursor-task-ls-message"), |
| 1994 | createdBy: "user", |
| 1995 | creationSource: "web", |
| 1996 | text: "List the workspace with a subagent.", |
| 1997 | attachments: [], |
| 1998 | }, |
| 1999 | }); |
| 2000 | const events = yield* runtime.events.pipe( |
| 2001 | Stream.takeUntil((event) => event.type === "turn.terminal"), |
| 2002 | Stream.runCollect, |
| 2003 | ); |
| 2004 | const terminal = events.find((event) => event.type === "turn.terminal"); |
| 2005 | assert.equal(terminal?.status, "completed"); |
| 2006 | const childThreadId = events.findLast((event) => event.type === "subagent.updated")?.subagent |
| 2007 | .childThreadId; |
| 2008 | assert.isDefined(childThreadId); |
| 2009 | assert.deepEqual( |
| 2010 | events.flatMap((event): ReadonlyArray<unknown> => { |
| 2011 | if (event.type !== "turn_item.updated" || event.turnItem.threadId !== childThreadId) { |
| 2012 | return []; |
| 2013 | } |
| 2014 | const item = event.turnItem; |
| 2015 | return item.type === "file_search" |
| 2016 | ? [{ status: item.status, pattern: item.pattern, results: item.results ?? [] }] |
| 2017 | : item.type === "dynamic_tool" |
| 2018 | ? [{ status: item.status, toolName: item.toolName, output: item.output }] |
| 2019 | : []; |
| 2020 | }), |
| 2021 | [ |
| 2022 | { |
| 2023 | status: "completed", |
| 2024 | pattern: workspace, |
| 2025 | results: [{ fileName: path.join(workspace, "src", "index.ts") }], |
| 2026 | }, |
| 2027 | { status: "completed", pattern: "", results: [] }, |
| 2028 | { status: "completed", pattern: "", results: [] }, |
| 2029 | { |
| 2030 | status: "completed", |
| 2031 | toolName: "mcp__docs__lookup", |
| 2032 | output: { content: [], isError: false }, |
| 2033 | }, |
| 2034 | ], |
| 2035 | ); |
| 2036 | }).pipe( |
| 2037 | Effect.scoped, |
| 2038 | Effect.provide( |
| 2039 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 2040 | ), |
| 2041 | ), |
| 2042 | ); |
| 2043 | |
| 2044 | it.effect("streams Cursor Task updates into the child thread before the task completes", () => |
| 2045 | Effect.gen(function* () { |
| 2046 | const read = { type: "read" as const, args: { path: "package.json" } }; |
| 2047 | const { events, childThreadId } = yield* runCursorTaskTurn( |
| 2048 | [ |
| 2049 | { type: "thinking-delta", text: "Reading package.json." }, |
| 2050 | { type: "thinking-completed", thinkingDurationMs: 1 }, |
| 2051 | { type: "text-delta", text: "Looking." }, |
| 2052 | { type: "step-completed", stepId: 1, stepDurationMs: 1 }, |
| 2053 | { type: "text-delta", text: "Reading it." }, |
| 2054 | { |
| 2055 | type: "tool-call-started", |
| 2056 | modelCallId: "nested", |
| 2057 | callId: "nested-read", |
| 2058 | toolCall: read, |
| 2059 | }, |
| 2060 | { |
| 2061 | type: "tool-call-completed", |
| 2062 | modelCallId: "nested", |
| 2063 | callId: "nested-read", |
| 2064 | toolCall: { |
| 2065 | ...read, |
| 2066 | result: { |
| 2067 | status: "success", |
| 2068 | value: { content: '{"name":"fixture"}', totalLines: 1, fileSize: 18 }, |
| 2069 | }, |
| 2070 | }, |
| 2071 | }, |
| 2072 | ], |
| 2073 | [ |
| 2074 | { assistantMessage: { text: "Looking." } }, |
| 2075 | { assistantMessage: { text: "Reading it." } }, |
| 2076 | { |
| 2077 | toolCall: { |
| 2078 | toolCallId: "nested-read", |
| 2079 | readToolCall: { args: { path: "package.json" }, result: { success: {} } }, |
| 2080 | }, |
| 2081 | }, |
| 2082 | { assistantMessage: { text: "The name is fixture." } }, |
| 2083 | ], |
| 2084 | ); |
| 2085 | const taskCompletedAt = events.findIndex( |
| 2086 | (event) => event.type === "subagent.updated" && event.subagent.status === "completed", |
| 2087 | ); |
| 2088 | const childItems = events.flatMap((event, index) => |
| 2089 | event.type === "turn_item.updated" && event.turnItem.threadId === childThreadId |
| 2090 | ? [{ index, item: event.turnItem }] |
| 2091 | : [], |
| 2092 | ); |
| 2093 | for (const type of ["reasoning", "dynamic_tool", "assistant_message"] as const) { |
| 2094 | assert.isTrue( |
| 2095 | childItems.some(({ index, item }) => item.type === type && index < taskCompletedAt), |
| 2096 | `${type} reached the child thread before the task completed`, |
| 2097 | ); |
| 2098 | } |
| 2099 | assert.deepEqual( |
| 2100 | childItems.flatMap(({ item }): ReadonlyArray<unknown> => |
| 2101 | item.status !== "completed" |
| 2102 | ? [] |
| 2103 | : item.type === "reasoning" || item.type === "assistant_message" |
| 2104 | ? [{ type: item.type, text: item.text }] |
| 2105 | : item.type === "dynamic_tool" |
| 2106 | ? [{ type: item.type, toolName: item.toolName }] |
| 2107 | : [], |
| 2108 | ), |
| 2109 | [ |
| 2110 | { type: "reasoning", text: "Reading package.json." }, |
| 2111 | { type: "assistant_message", text: "Looking." }, |
| 2112 | { type: "assistant_message", text: "Reading it." }, |
| 2113 | { type: "dynamic_tool", toolName: "Read" }, |
| 2114 | { type: "assistant_message", text: "The name is fixture." }, |
| 2115 | ], |
| 2116 | ); |
| 2117 | }).pipe( |
| 2118 | Effect.scoped, |
| 2119 | Effect.provide( |
| 2120 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 2121 | ), |
| 2122 | ), |
| 2123 | ); |
| 2124 | |
| 2125 | it.effect("fills a Cursor Task child from its saved steps where live updates fell short", () => |
| 2126 | Effect.gen(function* () { |
| 2127 | const { events, childThreadId } = yield* runCursorTaskTurn( |
| 2128 | [ |
| 2129 | { type: "step-started", stepId: 1 }, |
| 2130 | { |
| 2131 | type: "tool-call-started", |
| 2132 | modelCallId: "nested", |
| 2133 | callId: "open", |
| 2134 | toolCall: { type: "read", args: { path: "open.json" } }, |
| 2135 | }, |
| 2136 | { |
| 2137 | type: "tool-call-started", |
| 2138 | modelCallId: "nested", |
| 2139 | callId: "lost", |
| 2140 | toolCall: { type: "read", args: { path: "lost.json" } }, |
| 2141 | }, |
| 2142 | { |
| 2143 | type: "tool-call-completed", |
| 2144 | modelCallId: "nested", |
| 2145 | callId: "live", |
| 2146 | toolCall: { |
| 2147 | type: "read", |
| 2148 | args: { path: "live.json" }, |
| 2149 | result: { |
| 2150 | status: "success", |
| 2151 | value: { content: "{}", totalLines: 1, fileSize: 2 }, |
| 2152 | }, |
| 2153 | }, |
| 2154 | }, |
| 2155 | { type: "step-completed", stepId: 1, stepDurationMs: 1 }, |
| 2156 | ], |
| 2157 | [ |
| 2158 | { |
| 2159 | toolCall: { |
| 2160 | toolCallId: "open", |
| 2161 | readToolCall: { args: { path: "open.json" }, result: { success: {} } }, |
| 2162 | }, |
| 2163 | }, |
| 2164 | { |
| 2165 | toolCall: { |
| 2166 | toolCallId: "live", |
| 2167 | readToolCall: { args: { path: "live.json" }, result: { success: {} } }, |
| 2168 | }, |
| 2169 | }, |
| 2170 | { |
| 2171 | toolCall: { |
| 2172 | toolCallId: "saved", |
| 2173 | readToolCall: { args: { path: "saved.json" }, result: { success: {} } }, |
| 2174 | }, |
| 2175 | }, |
| 2176 | { assistantMessage: { text: "Saved answer." } }, |
| 2177 | ], |
| 2178 | ); |
| 2179 | const finalItems = new Map<string, string>(); |
| 2180 | for (const event of events) { |
| 2181 | if (event.type !== "turn_item.updated" || event.turnItem.threadId !== childThreadId) { |
| 2182 | continue; |
| 2183 | } |
| 2184 | const item = event.turnItem; |
| 2185 | if (item.type === "dynamic_tool") { |
| 2186 | finalItems.set(item.title ?? "", item.status); |
| 2187 | } else if (item.type === "assistant_message") { |
| 2188 | finalItems.set(item.text, item.status); |
| 2189 | } |
| 2190 | } |
| 2191 | assert.deepEqual(Object.fromEntries(finalItems), { |
| 2192 | "Read open.json": "completed", |
| 2193 | "Read lost.json": "interrupted", |
| 2194 | "Read live.json": "completed", |
| 2195 | "Read saved.json": "completed", |
| 2196 | "Saved answer.": "completed", |
| 2197 | }); |
| 2198 | }).pipe( |
| 2199 | Effect.scoped, |
| 2200 | Effect.provide( |
| 2201 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 2202 | ), |
| 2203 | ), |
| 2204 | ); |
| 2205 | |
| 2206 | it.effect("keeps the last 256 KiB of streamed shell output when the result carries none", () => |
| 2207 | Effect.gen(function* () { |
| 2208 | const fileSystem = yield* FileSystem.FileSystem; |
| 2209 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-shell-" }); |
| 2210 | const instanceId = ProviderInstanceId.make("cursor"); |
| 2211 | const threadId = ThreadId.make("cursor-shell-thread"); |
| 2212 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 2213 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 2214 | runtimeMode: "full-access", |
| 2215 | interactionMode: "default", |
| 2216 | cwd: workspace, |
| 2217 | }); |
| 2218 | const chunks = Array.from({ length: 3000 }, (_, index) => `${index}`.padEnd(255, ".") + "\n"); |
| 2219 | const shell = { |
| 2220 | type: "shell" as const, |
| 2221 | args: { command: "yes", workingDirectory: workspace }, |
| 2222 | }; |
| 2223 | const adapter = yield* makeCursorAdapterV2({ |
| 2224 | instanceId, |
| 2225 | environment: { HOME: workspace }, |
| 2226 | }).pipe( |
| 2227 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 2228 | assertComplete: Effect.void, |
| 2229 | open: () => |
| 2230 | Effect.succeed({ |
| 2231 | agentId: "native-cursor-shell", |
| 2232 | listMessages: Effect.succeed([]), |
| 2233 | close: Effect.void, |
| 2234 | send: (input) => |
| 2235 | Effect.gen(function* () { |
| 2236 | yield* input.onDelta!({ |
| 2237 | type: "tool-call-started", |
| 2238 | modelCallId: "model-call", |
| 2239 | callId: "shell-call", |
| 2240 | toolCall: shell, |
| 2241 | }); |
| 2242 | for (const chunk of chunks) { |
| 2243 | yield* input.onDelta!({ |
| 2244 | type: "shell-output-delta", |
| 2245 | event: { case: "stdout", value: { data: chunk }, toolCallId: "shell-call" }, |
| 2246 | }); |
| 2247 | } |
| 2248 | yield* input.onDelta!({ |
| 2249 | type: "tool-call-completed", |
| 2250 | modelCallId: "model-call", |
| 2251 | callId: "shell-call", |
| 2252 | toolCall: { |
| 2253 | ...shell, |
| 2254 | result: { |
| 2255 | status: "success", |
| 2256 | value: { |
| 2257 | exitCode: 0, |
| 2258 | signal: "", |
| 2259 | stdout: "", |
| 2260 | stderr: "", |
| 2261 | executionTime: 0, |
| 2262 | }, |
| 2263 | }, |
| 2264 | }, |
| 2265 | }); |
| 2266 | return { |
| 2267 | agentId: "native-cursor-shell", |
| 2268 | runId: "native-cursor-run", |
| 2269 | wait: Effect.succeed({ |
| 2270 | id: "native-cursor-run", |
| 2271 | requestId: "native-request", |
| 2272 | status: "finished" as const, |
| 2273 | durationMs: 1, |
| 2274 | }), |
| 2275 | cancel: Effect.void, |
| 2276 | }; |
| 2277 | }).pipe(Effect.orDie), |
| 2278 | }), |
| 2279 | }), |
| 2280 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 2281 | ); |
| 2282 | const runtime = yield* adapter.openSession({ |
| 2283 | threadId, |
| 2284 | providerSessionId: ProviderSessionId.make("cursor-shell-session"), |
| 2285 | modelSelection, |
| 2286 | runtimePolicy, |
| 2287 | }); |
| 2288 | const providerThread = yield* runtime.ensureThread({ |
| 2289 | threadId, |
| 2290 | modelSelection, |
| 2291 | runtimePolicy, |
| 2292 | }); |
| 2293 | const now = yield* DateTime.now; |
| 2294 | yield* runtime.startTurn({ |
| 2295 | threadId, |
| 2296 | providerThread, |
| 2297 | modelSelection, |
| 2298 | runtimePolicy, |
| 2299 | runId: RunId.make("cursor-shell-run"), |
| 2300 | runOrdinal: 1, |
| 2301 | providerTurnOrdinal: 1, |
| 2302 | attemptId: RunAttemptId.make("cursor-shell-attempt"), |
| 2303 | rootNodeId: NodeId.make("cursor-shell-root"), |
| 2304 | appThread: { |
| 2305 | id: threadId, |
| 2306 | projectId: ProjectId.make("cursor-shell-project"), |
| 2307 | createdBy: "user", |
| 2308 | creationSource: "web", |
| 2309 | title: "Cursor shell", |
| 2310 | providerInstanceId: instanceId, |
| 2311 | modelSelection, |
| 2312 | runtimeMode: "full-access", |
| 2313 | interactionMode: "default", |
| 2314 | branch: null, |
| 2315 | worktreePath: null, |
| 2316 | activeProviderThreadId: providerThread.id, |
| 2317 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 2318 | forkedFrom: null, |
| 2319 | createdAt: now, |
| 2320 | updatedAt: now, |
| 2321 | archivedAt: null, |
| 2322 | settledOverride: null, |
| 2323 | settledAt: null, |
| 2324 | lastVisitedAt: null, |
| 2325 | deletedAt: null, |
| 2326 | }, |
| 2327 | message: { |
| 2328 | messageId: MessageId.make("cursor-shell-message"), |
| 2329 | createdBy: "user", |
| 2330 | creationSource: "web", |
| 2331 | text: "hi", |
| 2332 | attachments: [], |
| 2333 | }, |
| 2334 | }); |
| 2335 | const events = yield* runtime.events.pipe( |
| 2336 | Stream.takeUntil((event) => event.type === "turn.terminal"), |
| 2337 | Stream.runCollect, |
| 2338 | ); |
| 2339 | const output = events |
| 2340 | .flatMap((event) => |
| 2341 | event.type === "turn_item.updated" && |
| 2342 | event.turnItem.type === "command_execution" && |
| 2343 | event.turnItem.status === "completed" |
| 2344 | ? [event.turnItem.output] |
| 2345 | : [], |
| 2346 | ) |
| 2347 | .at(-1); |
| 2348 | assert.equal(output, chunks.join("").slice(-256 * 1024)); |
| 2349 | }).pipe( |
| 2350 | Effect.scoped, |
| 2351 | Effect.provide( |
| 2352 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 2353 | ), |
| 2354 | ), |
| 2355 | ); |
| 2356 | |
| 2357 | it.effect( |
| 2358 | "lists background shells, holds for awaited ones, stops them on Stop or rollback and wakes when one exits", |
| 2359 | () => |
| 2360 | Effect.gen(function* () { |
| 2361 | const fileSystem = yield* FileSystem.FileSystem; |
| 2362 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ |
| 2363 | prefix: "cursor-v2-background-", |
| 2364 | }); |
| 2365 | const instanceId = ProviderInstanceId.make("cursor"); |
| 2366 | const threadId = ThreadId.make("cursor-background-thread"); |
| 2367 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 2368 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 2369 | runtimeMode: "full-access", |
| 2370 | interactionMode: "default", |
| 2371 | cwd: workspace, |
| 2372 | }); |
| 2373 | const wakes: Array<ProviderContinuationRequests.ProviderContinuationRequest> = []; |
| 2374 | const stopped: Array<string> = []; |
| 2375 | let report: ( |
| 2376 | event: CursorAgentSdk.CursorBackgroundShellEvent, |
| 2377 | ) => Effect.Effect<void> = () => Effect.void; |
| 2378 | const shell = (id: string) => ({ id, pid: Number(id) * 10, command: `sleep ${id}` }); |
| 2379 | const adapter = yield* makeCursorAdapterV2({ |
| 2380 | instanceId, |
| 2381 | environment: { HOME: workspace }, |
| 2382 | }).pipe( |
| 2383 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 2384 | assertComplete: Effect.void, |
| 2385 | open: () => |
| 2386 | Effect.succeed({ |
| 2387 | agentId: "native-cursor-background", |
| 2388 | listMessages: Effect.succeed([]), |
| 2389 | close: Effect.void, |
| 2390 | send: (input) => |
| 2391 | Effect.gen(function* () { |
| 2392 | report = input.onBackgroundShell!; |
| 2393 | for (const id of ["6", "7", "8"]) { |
| 2394 | yield* report({ |
| 2395 | ...shell(id), |
| 2396 | type: "started", |
| 2397 | stop: () => stopped.push(id), |
| 2398 | }); |
| 2399 | } |
| 2400 | return { |
| 2401 | agentId: "native-cursor-background", |
| 2402 | runId: "native-cursor-run", |
| 2403 | // Shell 6 exits after the agent's turn ended, before the run settles. |
| 2404 | wait: Effect.gen(function* () { |
| 2405 | yield* input.onDelta!({ type: "turn-ended" }).pipe(Effect.orDie); |
| 2406 | yield* report({ |
| 2407 | ...shell("6"), |
| 2408 | type: "ended", |
| 2409 | stopped: false, |
| 2410 | exitCode: 0, |
| 2411 | outputPath: undefined, |
| 2412 | }); |
| 2413 | return { |
| 2414 | id: "native-cursor-run", |
| 2415 | requestId: "native-request", |
| 2416 | status: "finished" as const, |
| 2417 | durationMs: 1, |
| 2418 | }; |
| 2419 | }), |
| 2420 | cancel: Effect.void, |
| 2421 | }; |
| 2422 | }), |
| 2423 | }), |
| 2424 | }), |
| 2425 | Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, { |
| 2426 | offer: (request) => Effect.sync(() => wakes.push(request)), |
| 2427 | take: Effect.never, |
| 2428 | }), |
| 2429 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 2430 | ); |
| 2431 | const runtime = yield* adapter.openSession({ |
| 2432 | threadId, |
| 2433 | providerSessionId: ProviderSessionId.make("cursor-background-session"), |
| 2434 | modelSelection, |
| 2435 | runtimePolicy, |
| 2436 | }); |
| 2437 | const providerThread = yield* runtime.ensureThread({ |
| 2438 | threadId, |
| 2439 | modelSelection, |
| 2440 | runtimePolicy, |
| 2441 | }); |
| 2442 | const now = yield* DateTime.now; |
| 2443 | yield* runtime.startTurn({ |
| 2444 | threadId, |
| 2445 | providerThread, |
| 2446 | modelSelection, |
| 2447 | runtimePolicy, |
| 2448 | runId: RunId.make("cursor-background-run"), |
| 2449 | runOrdinal: 1, |
| 2450 | providerTurnOrdinal: 1, |
| 2451 | attemptId: RunAttemptId.make("cursor-background-attempt"), |
| 2452 | rootNodeId: NodeId.make("cursor-background-root"), |
| 2453 | appThread: { |
| 2454 | id: threadId, |
| 2455 | projectId: ProjectId.make("cursor-background-project"), |
| 2456 | createdBy: "user", |
| 2457 | creationSource: "web", |
| 2458 | title: "Cursor shell", |
| 2459 | providerInstanceId: instanceId, |
| 2460 | modelSelection, |
| 2461 | runtimeMode: "full-access", |
| 2462 | interactionMode: "default", |
| 2463 | branch: null, |
| 2464 | worktreePath: null, |
| 2465 | activeProviderThreadId: providerThread.id, |
| 2466 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 2467 | forkedFrom: null, |
| 2468 | createdAt: now, |
| 2469 | updatedAt: now, |
| 2470 | archivedAt: null, |
| 2471 | settledOverride: null, |
| 2472 | settledAt: null, |
| 2473 | lastVisitedAt: null, |
| 2474 | deletedAt: null, |
| 2475 | }, |
| 2476 | message: { |
| 2477 | messageId: MessageId.make("cursor-background-message"), |
| 2478 | createdBy: "user", |
| 2479 | creationSource: "web", |
| 2480 | text: "hi", |
| 2481 | attachments: [], |
| 2482 | }, |
| 2483 | }); |
| 2484 | const events = yield* runtime.events.pipe( |
| 2485 | Stream.takeUntil((event) => event.type === "turn.terminal"), |
| 2486 | Stream.runCollect, |
| 2487 | ); |
| 2488 | const listed = ( |
| 2489 | update: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>, |
| 2490 | ): ReadonlyArray<unknown> => |
| 2491 | update.flatMap((event) => |
| 2492 | event.type === "provider_thread.updated" |
| 2493 | ? [ |
| 2494 | { |
| 2495 | tasks: (event.providerThread.pendingBackgroundTasks ?? []).map( |
| 2496 | ({ taskId, awaited }) => `${taskId}${awaited === true ? " awaited" : ""}`, |
| 2497 | ), |
| 2498 | sessionScoped: event.sessionScoped === true, |
| 2499 | }, |
| 2500 | ] |
| 2501 | : [], |
| 2502 | ); |
| 2503 | const nextUpdate = runtime.events.pipe( |
| 2504 | Stream.take(1), |
| 2505 | Stream.runCollect, |
| 2506 | Effect.map(listed), |
| 2507 | ); |
| 2508 | assert.deepStrictEqual(listed(events).at(-1), { tasks: ["7", "8"], sessionScoped: false }); |
| 2509 | // Idle release keeps the session while a shell runs. |
| 2510 | assert.isTrue(yield* runtime.hasPendingBackgroundWork!); |
| 2511 | |
| 2512 | // The agent names a shell by the pid Cursor showed it. |
| 2513 | assert.deepStrictEqual( |
| 2514 | yield* runtime.awaitBackgroundTasks!({ |
| 2515 | providerThread, |
| 2516 | taskIds: ["70", "missing"], |
| 2517 | awaited: true, |
| 2518 | }), |
| 2519 | { matched: ["70"] }, |
| 2520 | ); |
| 2521 | assert.deepStrictEqual(yield* nextUpdate, [ |
| 2522 | { tasks: ["7 awaited", "8"], sessionScoped: true }, |
| 2523 | ]); |
| 2524 | |
| 2525 | yield* report({ |
| 2526 | ...shell("8"), |
| 2527 | type: "ended", |
| 2528 | stopped: false, |
| 2529 | exitCode: 1, |
| 2530 | outputPath: "/terminals/8.txt", |
| 2531 | }); |
| 2532 | assert.deepStrictEqual(yield* nextUpdate, [{ tasks: ["7 awaited"], sessionScoped: true }]); |
| 2533 | |
| 2534 | // Rolling back stops what the discarded runs left running, so it cannot wake the thread. |
| 2535 | yield* runtime.rollbackThread({ |
| 2536 | providerThread, |
| 2537 | target: { |
| 2538 | type: "thread_start", |
| 2539 | checkpointId: CheckpointId.make("cursor-background-checkpoint"), |
| 2540 | appRunOrdinal: 0, |
| 2541 | }, |
| 2542 | providerThreadTurns: [], |
| 2543 | }); |
| 2544 | assert.deepStrictEqual(stopped, ["7"]); |
| 2545 | // A wake still queued when the rollback landed is dropped. |
| 2546 | assert.deepStrictEqual( |
| 2547 | yield* wakes[0]!.dispatchIfCurrent!(Effect.succeed("woken")), |
| 2548 | Option.none(), |
| 2549 | ); |
| 2550 | yield* report({ |
| 2551 | ...shell("7"), |
| 2552 | type: "ended", |
| 2553 | stopped: true, |
| 2554 | exitCode: undefined, |
| 2555 | outputPath: undefined, |
| 2556 | }); |
| 2557 | assert.deepStrictEqual(yield* nextUpdate, [{ tasks: [], sessionScoped: true }]); |
| 2558 | |
| 2559 | const terminal = events.find((event) => event.type === "turn.terminal"); |
| 2560 | assert.ok(terminal?.type === "turn.terminal"); |
| 2561 | yield* runtime.interruptTurn({ |
| 2562 | providerThread, |
| 2563 | providerTurnId: terminal.providerTurnId, |
| 2564 | requestRuntimeRestart: true, |
| 2565 | }); |
| 2566 | assert.deepStrictEqual(stopped, ["7"]); |
| 2567 | // A shell of the stopped run that is reported late is stopped, not kept. |
| 2568 | yield* report({ ...shell("9"), type: "started", stop: () => stopped.push("9") }); |
| 2569 | assert.deepStrictEqual(stopped, ["7", "9"]); |
| 2570 | assert.isFalse(yield* runtime.hasPendingBackgroundWork!); |
| 2571 | |
| 2572 | assert.deepStrictEqual( |
| 2573 | wakes.map(({ threadId, providerThreadId, delivery, detail, notification }) => ({ |
| 2574 | threadId, |
| 2575 | providerThreadId, |
| 2576 | delivery, |
| 2577 | detail, |
| 2578 | notification, |
| 2579 | })), |
| 2580 | [ |
| 2581 | { |
| 2582 | threadId, |
| 2583 | providerThreadId: providerThread.id, |
| 2584 | delivery: "message_text", |
| 2585 | detail: "Background command completed (exit 0): sleep 6", |
| 2586 | notification: { |
| 2587 | source: { kind: "command" }, |
| 2588 | outcome: "completed", |
| 2589 | summary: 'Command "sleep 6" finished (exit 0)', |
| 2590 | detail: "sleep 6", |
| 2591 | }, |
| 2592 | }, |
| 2593 | { |
| 2594 | threadId, |
| 2595 | providerThreadId: providerThread.id, |
| 2596 | delivery: "message_text", |
| 2597 | detail: "Background command completed (exit 1): sleep 8\n\nOutput: /terminals/8.txt", |
| 2598 | notification: { |
| 2599 | source: { kind: "command" }, |
| 2600 | outcome: "failed", |
| 2601 | summary: 'Command "sleep 8" failed (exit 1)', |
| 2602 | detail: "sleep 8", |
| 2603 | }, |
| 2604 | }, |
| 2605 | ], |
| 2606 | ); |
| 2607 | }).pipe( |
| 2608 | Effect.scoped, |
| 2609 | Effect.provide( |
| 2610 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 2611 | ), |
| 2612 | ), |
| 2613 | ); |
| 2614 | |
| 2615 | it.effect("names a custom model Cursor's account catalog rejects", () => |
| 2616 | Effect.gen(function* () { |
| 2617 | const fileSystem = yield* FileSystem.FileSystem; |
| 2618 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-model-" }); |
| 2619 | const instanceId = ProviderInstanceId.make("cursor"); |
| 2620 | const threadId = ThreadId.make("cursor-custom-model-thread"); |
| 2621 | const catalogModel = { instanceId, model: "composer-2.5" }; |
| 2622 | const customModel = { instanceId, model: "deepseek/deepseek-v4.1-flash" }; |
| 2623 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 2624 | runtimeMode: "full-access", |
| 2625 | interactionMode: "default", |
| 2626 | cwd: workspace, |
| 2627 | }); |
| 2628 | // The SDK checks every create, resume, and send model against the account catalog. |
| 2629 | const checkModel = (method: string, model: { readonly id: string } | undefined) => |
| 2630 | model === undefined || model.id === "composer-2.5" |
| 2631 | ? Effect.void |
| 2632 | : Effect.fail( |
| 2633 | new CursorAgentSdk.CursorAgentSdkRunnerError({ |
| 2634 | method, |
| 2635 | cause: new ConfigurationError( |
| 2636 | `Cannot use this model: ${model.id}. Available models: default, composer-2.5. Use Cursor.models.list() to discover valid selections.`, |
| 2637 | { isRetryable: false }, |
| 2638 | ), |
| 2639 | }), |
| 2640 | ); |
| 2641 | const adapter = yield* makeCursorAdapterV2({ |
| 2642 | instanceId, |
| 2643 | environment: { HOME: workspace }, |
| 2644 | }).pipe( |
| 2645 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 2646 | assertComplete: Effect.void, |
| 2647 | open: (input) => |
| 2648 | checkModel(`agent.${input.operation}`, input.options.model).pipe( |
| 2649 | Effect.as({ |
| 2650 | agentId: "native-cursor-custom-model", |
| 2651 | listMessages: Effect.succeed([]), |
| 2652 | close: Effect.void, |
| 2653 | send: (sendInput) => |
| 2654 | checkModel("run.start", sendInput.options?.model).pipe( |
| 2655 | Effect.andThen(Effect.die("unexpected Cursor run")), |
| 2656 | ), |
| 2657 | }), |
| 2658 | ), |
| 2659 | }), |
| 2660 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 2661 | ); |
| 2662 | const runtime = yield* adapter.openSession({ |
| 2663 | threadId, |
| 2664 | providerSessionId: ProviderSessionId.make("cursor-custom-model-session"), |
| 2665 | modelSelection: catalogModel, |
| 2666 | runtimePolicy, |
| 2667 | }); |
| 2668 | const expected = |
| 2669 | 'Cursor cannot run the model "deepseek/deepseek-v4.1-flash". Cursor only runs models from your Cursor account. Choose one of those, or use OpenCode for OpenRouter and other API-key models.'; |
| 2670 | |
| 2671 | const createFailure = yield* runtime |
| 2672 | .ensureThread({ threadId, modelSelection: customModel, runtimePolicy }) |
| 2673 | .pipe(Effect.flip); |
| 2674 | assert.equal(makeProviderFailure({ cause: createFailure }).message, expected); |
| 2675 | |
| 2676 | const providerThread = yield* runtime.ensureThread({ |
| 2677 | threadId, |
| 2678 | modelSelection: catalogModel, |
| 2679 | runtimePolicy, |
| 2680 | }); |
| 2681 | const now = yield* DateTime.now; |
| 2682 | const sendFailure = yield* runtime |
| 2683 | .startTurn({ |
| 2684 | threadId, |
| 2685 | providerThread, |
| 2686 | modelSelection: customModel, |
| 2687 | runtimePolicy, |
| 2688 | runId: RunId.make("cursor-custom-model-run"), |
| 2689 | runOrdinal: 1, |
| 2690 | providerTurnOrdinal: 1, |
| 2691 | attemptId: RunAttemptId.make("cursor-custom-model-attempt"), |
| 2692 | rootNodeId: NodeId.make("cursor-custom-model-root"), |
| 2693 | appThread: { |
| 2694 | id: threadId, |
| 2695 | projectId: ProjectId.make("cursor-custom-model-project"), |
| 2696 | createdBy: "user", |
| 2697 | creationSource: "web", |
| 2698 | title: "Cursor custom model", |
| 2699 | providerInstanceId: instanceId, |
| 2700 | modelSelection: customModel, |
| 2701 | runtimeMode: "full-access", |
| 2702 | interactionMode: "default", |
| 2703 | branch: null, |
| 2704 | worktreePath: null, |
| 2705 | activeProviderThreadId: providerThread.id, |
| 2706 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 2707 | forkedFrom: null, |
| 2708 | createdAt: now, |
| 2709 | updatedAt: now, |
| 2710 | archivedAt: null, |
| 2711 | settledOverride: null, |
| 2712 | settledAt: null, |
| 2713 | lastVisitedAt: null, |
| 2714 | deletedAt: null, |
| 2715 | }, |
| 2716 | message: { |
| 2717 | messageId: MessageId.make("cursor-custom-model-message"), |
| 2718 | createdBy: "user", |
| 2719 | creationSource: "web", |
| 2720 | text: "Hello.", |
| 2721 | attachments: [], |
| 2722 | }, |
| 2723 | }) |
| 2724 | .pipe(Effect.flip); |
| 2725 | assert.equal(makeProviderFailure({ cause: sendFailure }).message, expected); |
| 2726 | }).pipe( |
| 2727 | Effect.scoped, |
| 2728 | Effect.provide( |
| 2729 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 2730 | ), |
| 2731 | ), |
| 2732 | ); |
| 2733 | |
| 2734 | it.live("honors the user's Cursor CLI attribution preferences", () => |
| 2735 | Effect.gen(function* () { |
| 2736 | const fileSystem = yield* FileSystem.FileSystem; |
| 2737 | const path = yield* Path.Path; |
| 2738 | const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-attribution-" }); |
| 2739 | yield* fileSystem.makeDirectory(path.join(home, ".cursor")); |
| 2740 | yield* fileSystem.writeFileString( |
| 2741 | path.join(home, ".cursor", "cli-config.json"), |
| 2742 | JSON.stringify({ |
| 2743 | attribution: { attributeCommitsToAgent: false, attributePRsToAgent: false }, |
| 2744 | }), |
| 2745 | ); |
| 2746 | const backend = yield* fakeCursorBackend; |
| 2747 | // CURSOR_CONFIG_DIR outranks an ambient XDG_CONFIG_HOME; the home overrides keep the real ~/.cursor out. |
| 2748 | yield* scopedProcessEnv({ |
| 2749 | HOME: home, |
| 2750 | USERPROFILE: home, |
| 2751 | CURSOR_CONFIG_DIR: path.join(home, ".cursor"), |
| 2752 | }); |
| 2753 | const agent = yield* Effect.acquireRelease( |
| 2754 | Effect.promise(() => |
| 2755 | Agent.create( |
| 2756 | makeCursorAgentOptions({ |
| 2757 | apiKey: "synthetic-cursor-api-key", |
| 2758 | modelSelection: { |
| 2759 | instanceId: ProviderInstanceId.make("cursor"), |
| 2760 | model: "composer-2", |
| 2761 | }, |
| 2762 | runtimePolicy: { |
| 2763 | runtimeMode: "full-access", |
| 2764 | interactionMode: "default", |
| 2765 | cwd: home, |
| 2766 | }, |
| 2767 | threadId: ThreadId.make("cursor-attribution-thread"), |
| 2768 | mcpSession: undefined, |
| 2769 | platform: "linux", |
| 2770 | }), |
| 2771 | ), |
| 2772 | ), |
| 2773 | (agent) => Effect.sync(() => agent.close()), |
| 2774 | ); |
| 2775 | yield* Effect.promise(() => agent.send("Commit hello.txt.")); |
| 2776 | |
| 2777 | assert.deepEqual(yield* Deferred.await(backend.requestContext), { |
| 2778 | commitAttributionMessage: undefined, |
| 2779 | prAttributionMessage: undefined, |
| 2780 | }); |
| 2781 | }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), |
| 2782 | ); |
| 2783 | |
| 2784 | it.live("opens a model added to the account after its workspace already ran an agent", () => |
| 2785 | Effect.gen(function* () { |
| 2786 | const fileSystem = yield* FileSystem.FileSystem; |
| 2787 | const path = yield* Path.Path; |
| 2788 | const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-new-model-" }); |
| 2789 | const backend = yield* fakeCursorBackend; |
| 2790 | yield* scopedProcessEnv({ |
| 2791 | HOME: home, |
| 2792 | USERPROFILE: home, |
| 2793 | CURSOR_CONFIG_DIR: path.join(home, ".cursor"), |
| 2794 | }); |
| 2795 | const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe( |
| 2796 | Effect.provide(CursorSdk.layer), |
| 2797 | ); |
| 2798 | const open = (model: string) => |
| 2799 | Effect.acquireRelease( |
| 2800 | runner.open({ |
| 2801 | operation: "create", |
| 2802 | options: makeCursorAgentOptions({ |
| 2803 | apiKey: "synthetic-cursor-api-key", |
| 2804 | modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model }, |
| 2805 | runtimePolicy: { |
| 2806 | runtimeMode: "full-access", |
| 2807 | interactionMode: "default", |
| 2808 | cwd: home, |
| 2809 | }, |
| 2810 | threadId: ThreadId.make(`cursor-new-model-${model}`), |
| 2811 | mcpSession: undefined, |
| 2812 | platform: "linux", |
| 2813 | }), |
| 2814 | threadId: ThreadId.make(`cursor-new-model-${model}`), |
| 2815 | providerSessionId: ProviderSessionId.make(`cursor-new-model-${model}`), |
| 2816 | }), |
| 2817 | (session) => Effect.ignore(session.close), |
| 2818 | ); |
| 2819 | |
| 2820 | yield* open("composer-2"); |
| 2821 | backend.models.push("composer-2.5"); |
| 2822 | |
| 2823 | const exit = yield* Effect.exit(open("composer-2.5")); |
| 2824 | assert.isTrue( |
| 2825 | Exit.isSuccess(exit), |
| 2826 | Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "opened", |
| 2827 | ); |
| 2828 | }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), |
| 2829 | ); |
| 2830 | |
| 2831 | it("maps runtime modes to the SDK sandbox and auto-review controls", () => { |
| 2832 | const base = { |
| 2833 | interactionMode: "default" as const, |
| 2834 | cwd: "/tmp/cursor-adapter", |
| 2835 | }; |
| 2836 | assert.deepEqual( |
| 2837 | cursorRuntimeAgentPolicy( |
| 2838 | { |
| 2839 | ...base, |
| 2840 | runtimeMode: "full-access", |
| 2841 | }, |
| 2842 | "linux", |
| 2843 | ), |
| 2844 | { |
| 2845 | autoReview: false, |
| 2846 | sandboxEnabled: false, |
| 2847 | }, |
| 2848 | ); |
| 2849 | assert.deepEqual( |
| 2850 | cursorRuntimeAgentPolicy( |
| 2851 | { |
| 2852 | ...base, |
| 2853 | runtimeMode: "auto-accept-edits", |
| 2854 | }, |
| 2855 | "linux", |
| 2856 | ), |
| 2857 | { |
| 2858 | autoReview: false, |
| 2859 | sandboxEnabled: true, |
| 2860 | }, |
| 2861 | ); |
| 2862 | assert.deepEqual( |
| 2863 | cursorRuntimeAgentPolicy( |
| 2864 | { |
| 2865 | ...base, |
| 2866 | runtimeMode: "auto", |
| 2867 | }, |
| 2868 | "linux", |
| 2869 | ), |
| 2870 | { |
| 2871 | autoReview: true, |
| 2872 | sandboxEnabled: true, |
| 2873 | }, |
| 2874 | ); |
| 2875 | assert.deepEqual( |
| 2876 | cursorRuntimeAgentPolicy( |
| 2877 | { |
| 2878 | ...base, |
| 2879 | runtimeMode: "approval-required", |
| 2880 | }, |
| 2881 | "linux", |
| 2882 | ), |
| 2883 | { |
| 2884 | autoReview: true, |
| 2885 | sandboxEnabled: true, |
| 2886 | }, |
| 2887 | ); |
| 2888 | assert.deepEqual( |
| 2889 | cursorRuntimeAgentPolicy( |
| 2890 | { |
| 2891 | ...base, |
| 2892 | runtimeMode: "full-access", |
| 2893 | approvalPolicy: "never", |
| 2894 | sandboxPolicy: { type: "readOnly" }, |
| 2895 | }, |
| 2896 | "linux", |
| 2897 | ), |
| 2898 | { |
| 2899 | autoReview: false, |
| 2900 | sandboxEnabled: true, |
| 2901 | }, |
| 2902 | ); |
| 2903 | assert.deepEqual( |
| 2904 | cursorRuntimeAgentPolicy( |
| 2905 | { |
| 2906 | ...base, |
| 2907 | runtimeMode: "approval-required", |
| 2908 | approvalPolicy: "never", |
| 2909 | sandboxPolicy: { type: "dangerFullAccess" }, |
| 2910 | }, |
| 2911 | "linux", |
| 2912 | ), |
| 2913 | { |
| 2914 | autoReview: false, |
| 2915 | sandboxEnabled: false, |
| 2916 | }, |
| 2917 | ); |
| 2918 | assert.deepEqual( |
| 2919 | cursorRuntimeAgentPolicy( |
| 2920 | { |
| 2921 | ...base, |
| 2922 | runtimeMode: "auto-accept-edits", |
| 2923 | }, |
| 2924 | "win32", |
| 2925 | ), |
| 2926 | { |
| 2927 | autoReview: false, |
| 2928 | sandboxEnabled: true, |
| 2929 | }, |
| 2930 | ); |
| 2931 | assert.deepEqual( |
| 2932 | cursorRuntimeAgentPolicy( |
| 2933 | { |
| 2934 | ...base, |
| 2935 | runtimeMode: "auto", |
| 2936 | approvalPolicy: "never", |
| 2937 | }, |
| 2938 | "win32", |
| 2939 | ), |
| 2940 | { |
| 2941 | autoReview: false, |
| 2942 | sandboxEnabled: true, |
| 2943 | }, |
| 2944 | ); |
| 2945 | // Auto-review can gate Windows execution without the unsupported SDK sandbox. |
| 2946 | assert.deepEqual( |
| 2947 | cursorRuntimeAgentPolicy( |
| 2948 | { |
| 2949 | ...base, |
| 2950 | runtimeMode: "auto", |
| 2951 | }, |
| 2952 | "win32", |
| 2953 | ), |
| 2954 | { |
| 2955 | autoReview: true, |
| 2956 | sandboxEnabled: false, |
| 2957 | }, |
| 2958 | ); |
| 2959 | assert.deepEqual( |
| 2960 | cursorRuntimeAgentPolicy( |
| 2961 | { |
| 2962 | ...base, |
| 2963 | runtimeMode: "auto", |
| 2964 | sandboxPolicy: { type: "workspaceWrite" }, |
| 2965 | }, |
| 2966 | "win32", |
| 2967 | ), |
| 2968 | { |
| 2969 | autoReview: true, |
| 2970 | sandboxEnabled: true, |
| 2971 | }, |
| 2972 | ); |
| 2973 | }); |
| 2974 | |
| 2975 | it("injects thread-scoped MCP credentials without logging them", () => { |
| 2976 | const threadId = ThreadId.make("thread-cursor-mcp"); |
| 2977 | const mcpSession = { |
| 2978 | environmentId: EnvironmentId.make("environment-cursor-mcp"), |
| 2979 | threadId, |
| 2980 | providerSessionId: "mcp-session-cursor", |
| 2981 | providerInstanceId: ProviderInstanceId.make("cursor"), |
| 2982 | endpoint: "http://127.0.0.1:43123/mcp", |
| 2983 | authorizationHeader: "Bearer secret-cursor-mcp-token", |
| 2984 | browserToolsAvailable: true, |
| 2985 | }; |
| 2986 | |
| 2987 | assert.deepEqual(cursorMcpServers(mcpSession), { |
| 2988 | "t3-code": { |
| 2989 | type: "http", |
| 2990 | url: "http://127.0.0.1:43123/mcp", |
| 2991 | headers: { |
| 2992 | Authorization: "Bearer secret-cursor-mcp-token", |
| 2993 | }, |
| 2994 | }, |
| 2995 | }); |
| 2996 | |
| 2997 | const options = makeCursorAgentOptions({ |
| 2998 | apiKey: "secret-cursor-api-key", |
| 2999 | modelSelection: { |
| 3000 | instanceId: ProviderInstanceId.make("cursor"), |
| 3001 | model: "composer-2.5", |
| 3002 | }, |
| 3003 | runtimePolicy: { |
| 3004 | runtimeMode: "full-access", |
| 3005 | interactionMode: "default", |
| 3006 | cwd: "/workspace", |
| 3007 | }, |
| 3008 | threadId, |
| 3009 | mcpSession, |
| 3010 | platform: "linux", |
| 3011 | }); |
| 3012 | assert.deepEqual(options.mcpServers, cursorMcpServers(mcpSession)); |
| 3013 | |
| 3014 | const logged = JSON.stringify(CursorAgentSdk.loggedCursorAgentOptions(options)); |
| 3015 | assert.notInclude(logged, "secret-cursor-api-key"); |
| 3016 | assert.notInclude(logged, "secret-cursor-mcp-token"); |
| 3017 | }); |
| 3018 | |
| 3019 | it("loads project settings only when runtime policy permits unrestricted execution", () => { |
| 3020 | const input = { |
| 3021 | modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2.5" }, |
| 3022 | threadId: ThreadId.make("cursor-project-settings"), |
| 3023 | mcpSession: undefined, |
| 3024 | platform: "linux" as const, |
| 3025 | }; |
| 3026 | const policy = { cwd: "/workspace", interactionMode: "default" as const }; |
| 3027 | for (const runtimeMode of [ |
| 3028 | "approval-required", |
| 3029 | "auto", |
| 3030 | "auto-accept-edits", |
| 3031 | "full-access", |
| 3032 | ] as const) { |
| 3033 | const options = makeCursorAgentOptions({ |
| 3034 | ...input, |
| 3035 | runtimePolicy: { ...policy, runtimeMode }, |
| 3036 | }); |
| 3037 | assert.equal( |
| 3038 | options.local?.settingSources?.includes("project"), |
| 3039 | runtimeMode === "full-access", |
| 3040 | ); |
| 3041 | } |
| 3042 | const unrestrictedOverrides = makeCursorAgentOptions({ |
| 3043 | ...input, |
| 3044 | runtimePolicy: { |
| 3045 | ...policy, |
| 3046 | runtimeMode: "auto-accept-edits", |
| 3047 | approvalPolicy: "never", |
| 3048 | sandboxPolicy: { type: "dangerFullAccess" }, |
| 3049 | }, |
| 3050 | }); |
| 3051 | assert.notInclude(unrestrictedOverrides.local?.settingSources ?? [], "project"); |
| 3052 | for (const restriction of [ |
| 3053 | { approvalPolicy: "on-request" as const }, |
| 3054 | { sandboxPolicy: { type: "readOnly" as const } }, |
| 3055 | ]) { |
| 3056 | const options = makeCursorAgentOptions({ |
| 3057 | ...input, |
| 3058 | runtimePolicy: { ...policy, runtimeMode: "full-access", ...restriction }, |
| 3059 | }); |
| 3060 | assert.notInclude(options.local?.settingSources ?? [], "project"); |
| 3061 | } |
| 3062 | }); |
| 3063 | |
| 3064 | it.effect.skipIf(!symlinksSupported)( |
| 3065 | "starts mcp.json servers that use Cursor's workspace variables", |
| 3066 | () => |
| 3067 | Effect.gen(function* () { |
| 3068 | const fileSystem = yield* FileSystem.FileSystem; |
| 3069 | const path = yield* Path.Path; |
| 3070 | const scratch = yield* fileSystem.realPath( |
| 3071 | yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-mcp-" }), |
| 3072 | ); |
| 3073 | const workspace = path.join(scratch, "workspace"); |
| 3074 | const home = path.join(scratch, "home"); |
| 3075 | const loadServers = () => |
| 3076 | cursorWorkspaceMcpServers(cwd, { MCP_TYPE: "stdio" }).pipe( |
| 3077 | Effect.provideService(HostProcess.HomeDirectory, home), |
| 3078 | Effect.provideService(HostProcess.Environment, {}), |
| 3079 | ); |
| 3080 | // Cursor resolves the project root through symlinks, as git does. |
| 3081 | yield* fileSystem.makeDirectory(path.join(workspace, "packages", "app"), { |
| 3082 | recursive: true, |
| 3083 | }); |
| 3084 | yield* fileSystem.symlink(workspace, path.join(scratch, "link")); |
| 3085 | const cwd = path.join(scratch, "link", "packages", "app"); |
| 3086 | yield* spawnAndCollect("git", ChildProcess.make("git", ["init", workspace])); |
| 3087 | // Git prints forward slashes on Windows, and the loader passes its spelling through. |
| 3088 | const projectRoot = (yield* spawnAndCollect( |
| 3089 | "git", |
| 3090 | ChildProcess.make("git", ["rev-parse", "--show-toplevel"], { cwd }), |
| 3091 | )).stdout.trim(); |
| 3092 | yield* fileSystem.makeDirectory(path.join(workspace, ".cursor"), { recursive: true }); |
| 3093 | yield* fileSystem.makeDirectory(path.join(home, ".cursor"), { recursive: true }); |
| 3094 | yield* fileSystem.writeFileString( |
| 3095 | path.join(workspace, ".cursor", "mcp.json"), |
| 3096 | `{ |
| 3097 | // Cursor's editor accepts comments here. |
| 3098 | "mcpServers": { |
| 3099 | "repro": { "command": "node", "args": ["\${workspaceFolder}/server.mjs"], "startupTimeoutSec": 120 }, |
| 3100 | "plain": { "command": "node", "args": ["server.mjs"] }, |
| 3101 | "argument-only": { "command": "node", "args": ["server.mjs", "--workspace", "\${workspaceFolder}"] }, |
| 3102 | "env-only": { "command": "node", "args": ["server.mjs"], "env": { "PROJECT_ROOT": "\${workspaceFolder}" } }, |
| 3103 | "cwd-only": { "command": "node", "args": ["server.mjs"], "cwd": "\${workspaceFolder}" }, |
| 3104 | "unset-env": { "command": "node", "env": { "CONFIG": "\${env:T3_MCP_UNSET}" } }, |
| 3105 | "wrapped": { "command": "proto", "args": ["run", "node", "--", "\${workspaceFolder}/server.mjs"] }, |
| 3106 | "label": { "command": "node", "args": ["server.mjs", "--label", "\${workspaceFolder}/client"] }, |
| 3107 | "env-file": { "command": "node", "args": ["\${workspaceFolder}/server.mjs"], "envFile": ".env.mcp" }, |
| 3108 | "tool-filter": { "command": "node", "args": ["\${workspaceFolder}/server.mjs"], "enabledTools": ["read_file"] }, |
| 3109 | "off": { "command": "node", "args": ["\${workspaceFolder}/off.mjs"] }, |
| 3110 | "typed": { "type": "\${env:MCP_TYPE}", "command": "node", "args": ["server.mjs"] }, |
| 3111 | "plugin-docs-search": { "command": "node", "args": ["\${workspaceFolder}/search.mjs"] }, |
| 3112 | }, |
| 3113 | }`, |
| 3114 | ); |
| 3115 | yield* fileSystem.writeFileString( |
| 3116 | path.join(home, ".cursor", "mcp.json"), |
| 3117 | JSON.stringify({ |
| 3118 | mcpServers: { |
| 3119 | repro: { command: "node", args: ["${userHome}/shadowed.mjs"] }, |
| 3120 | docs: { |
| 3121 | url: "https://docs.example/${workspaceFolderBasename}", |
| 3122 | headers: { Authorization: "Bearer ${env:DOCS_TOKEN}" }, |
| 3123 | tls: { caBundle: "${userHome}/ca.pem" }, |
| 3124 | }, |
| 3125 | }, |
| 3126 | }), |
| 3127 | ); |
| 3128 | // Cursor keeps per-project state under a directory named after the project path. |
| 3129 | const projectDirectory = workspace.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-|-$/g, ""); |
| 3130 | yield* fileSystem.makeDirectory(path.join(home, ".cursor", "projects", projectDirectory), { |
| 3131 | recursive: true, |
| 3132 | }); |
| 3133 | yield* fileSystem.writeFileString( |
| 3134 | path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), |
| 3135 | JSON.stringify(["off"]), |
| 3136 | ); |
| 3137 | |
| 3138 | const instanceId = ProviderInstanceId.make("cursor"); |
| 3139 | const threadId = ThreadId.make("cursor-mcp-thread"); |
| 3140 | const mcpSessions = yield* McpProviderSessions.McpProviderSessions; |
| 3141 | yield* mcpSessions.set({ |
| 3142 | environmentId: EnvironmentId.make("cursor-mcp-environment"), |
| 3143 | threadId, |
| 3144 | providerSessionId: "cursor-mcp-session", |
| 3145 | providerInstanceId: instanceId, |
| 3146 | endpoint: "http://127.0.0.1:43123/mcp", |
| 3147 | authorizationHeader: "Bearer synthetic-cursor-token", |
| 3148 | browserToolsAvailable: false, |
| 3149 | }); |
| 3150 | const t3Servers = cursorMcpServers(yield* mcpSessions.read(threadId)); |
| 3151 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 3152 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 3153 | runtimeMode: "full-access", |
| 3154 | interactionMode: "default", |
| 3155 | cwd, |
| 3156 | }); |
| 3157 | let openedWith: CursorAgentSdk.CursorAgentSdkOpenInput["options"] | undefined; |
| 3158 | const sentWith: Array<Record<string, unknown> | undefined> = []; |
| 3159 | const adapter = yield* makeCursorAdapterV2({ |
| 3160 | instanceId, |
| 3161 | environment: { |
| 3162 | HOME: path.join(scratch, "override"), |
| 3163 | CURSOR_DATA_DIR: path.join(scratch, "override"), |
| 3164 | DOCS_TOKEN: "docs-token", |
| 3165 | MCP_TYPE: "stdio", |
| 3166 | }, |
| 3167 | }).pipe( |
| 3168 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 3169 | assertComplete: Effect.void, |
| 3170 | open: (input) => |
| 3171 | Effect.sync(() => { |
| 3172 | openedWith = input.options; |
| 3173 | return { |
| 3174 | agentId: "native-cursor-mcp", |
| 3175 | listMessages: Effect.succeed([]), |
| 3176 | close: Effect.void, |
| 3177 | send: (sendInput) => { |
| 3178 | sentWith.push(sendInput.options?.mcpServers); |
| 3179 | return Effect.die("sent"); |
| 3180 | }, |
| 3181 | }; |
| 3182 | }), |
| 3183 | }), |
| 3184 | Effect.provide(TestProviderHost.layer({ cwd })), |
| 3185 | ); |
| 3186 | const runtime = yield* adapter.openSession({ |
| 3187 | threadId, |
| 3188 | providerSessionId: ProviderSessionId.make("cursor-mcp-session"), |
| 3189 | modelSelection, |
| 3190 | runtimePolicy, |
| 3191 | }); |
| 3192 | const providerThread = yield* runtime |
| 3193 | .ensureThread({ threadId, modelSelection, runtimePolicy }) |
| 3194 | .pipe( |
| 3195 | Effect.provideService(HostProcess.HomeDirectory, home), |
| 3196 | Effect.provideService(HostProcess.Environment, {}), |
| 3197 | ); |
| 3198 | const now = yield* DateTime.now; |
| 3199 | const sendTurn = (ordinal: number) => |
| 3200 | runtime |
| 3201 | .startTurn({ |
| 3202 | threadId, |
| 3203 | providerThread, |
| 3204 | modelSelection, |
| 3205 | runtimePolicy, |
| 3206 | runId: RunId.make(`cursor-mcp-run-${ordinal}`), |
| 3207 | runOrdinal: ordinal, |
| 3208 | providerTurnOrdinal: ordinal, |
| 3209 | attemptId: RunAttemptId.make(`cursor-mcp-attempt-${ordinal}`), |
| 3210 | rootNodeId: NodeId.make(`cursor-mcp-root-${ordinal}`), |
| 3211 | appThread: { |
| 3212 | id: threadId, |
| 3213 | projectId: ProjectId.make("cursor-mcp-project"), |
| 3214 | createdBy: "user", |
| 3215 | creationSource: "web", |
| 3216 | title: "Cursor MCP", |
| 3217 | providerInstanceId: instanceId, |
| 3218 | modelSelection, |
| 3219 | runtimeMode: "full-access", |
| 3220 | interactionMode: "default", |
| 3221 | branch: null, |
| 3222 | worktreePath: null, |
| 3223 | activeProviderThreadId: providerThread.id, |
| 3224 | lineage: { |
| 3225 | parentThreadId: null, |
| 3226 | relationshipToParent: null, |
| 3227 | rootThreadId: threadId, |
| 3228 | }, |
| 3229 | forkedFrom: null, |
| 3230 | createdAt: now, |
| 3231 | updatedAt: now, |
| 3232 | archivedAt: null, |
| 3233 | settledOverride: null, |
| 3234 | settledAt: null, |
| 3235 | lastVisitedAt: null, |
| 3236 | deletedAt: null, |
| 3237 | }, |
| 3238 | message: { |
| 3239 | messageId: MessageId.make(`cursor-mcp-message-${ordinal}`), |
| 3240 | createdBy: "user", |
| 3241 | creationSource: "web", |
| 3242 | text: "Hello.", |
| 3243 | attachments: [], |
| 3244 | }, |
| 3245 | }) |
| 3246 | .pipe( |
| 3247 | Effect.exit, |
| 3248 | Effect.provideService(HostProcess.HomeDirectory, home), |
| 3249 | Effect.provideService(HostProcess.Environment, {}), |
| 3250 | ); |
| 3251 | |
| 3252 | const expectedServers = { |
| 3253 | repro: { |
| 3254 | command: "node", |
| 3255 | args: [`${projectRoot}/server.mjs`], |
| 3256 | startupTimeoutSec: 120, |
| 3257 | cwd: projectRoot, |
| 3258 | }, |
| 3259 | "cwd-only": { command: "node", args: ["server.mjs"], cwd: projectRoot }, |
| 3260 | }; |
| 3261 | // The agent is created with T3's server only; the resolved servers go with each turn. |
| 3262 | assert.deepEqual(openedWith?.mcpServers, t3Servers); |
| 3263 | yield* sendTurn(1); |
| 3264 | assert.deepEqual(sentWith[0], { ...expectedServers, ...t3Servers }); |
| 3265 | // A server switched off between turns stays off on the next one. |
| 3266 | yield* fileSystem.writeFileString( |
| 3267 | path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), |
| 3268 | JSON.stringify(["off", "repro"]), |
| 3269 | ); |
| 3270 | yield* sendTurn(2); |
| 3271 | const { repro: _disabled, ...stillEnabled } = expectedServers; |
| 3272 | assert.deepEqual(sentWith[1], { ...stillEnabled, ...t3Servers }); |
| 3273 | // Unreadable disabled state starts none of the overrides, and the turn still goes out. |
| 3274 | yield* fileSystem.writeFileString( |
| 3275 | path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), |
| 3276 | "[", |
| 3277 | ); |
| 3278 | yield* sendTurn(3); |
| 3279 | assert.deepEqual(sentWith[2], t3Servers); |
| 3280 | yield* fileSystem.writeFileString( |
| 3281 | path.join(workspace, ".cursor", "mcp.json"), |
| 3282 | JSON.stringify({ mcpServers: { plain: { command: "node", args: ["server.mjs"] } } }), |
| 3283 | ); |
| 3284 | yield* fileSystem.remove(path.join(home, ".cursor", "mcp.json")); |
| 3285 | assert.deepEqual(yield* loadServers(), {}); |
| 3286 | }).pipe( |
| 3287 | Effect.scoped, |
| 3288 | Effect.provide( |
| 3289 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 3290 | ), |
| 3291 | ), |
| 3292 | ); |
| 3293 | |
| 3294 | it("recognizes direct and SDK-wrapped abort failures as cancellation", () => { |
| 3295 | assert.isTrue(CursorAgentSdk.isCursorCancellationError({ name: "AbortError" })); |
| 3296 | assert.isTrue( |
| 3297 | CursorAgentSdk.isCursorCancellationError({ |
| 3298 | name: "ConnectError", |
| 3299 | cause: { |
| 3300 | name: "ConnectError", |
| 3301 | cause: { name: "AbortError" }, |
| 3302 | }, |
| 3303 | }), |
| 3304 | ); |
| 3305 | assert.isFalse(CursorAgentSdk.isCursorCancellationError(new Error("request failed"))); |
| 3306 | assert.isFalse(CursorAgentSdk.isCursorCancellationError(null)); |
| 3307 | }); |
| 3308 | |
| 3309 | it.effect( |
| 3310 | "rewrites skills on live steers and returns a decline without waiting for completion", |
| 3311 | () => |
| 3312 | Effect.gen(function* () { |
| 3313 | const fileSystem = yield* FileSystem.FileSystem; |
| 3314 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ |
| 3315 | prefix: "cursor-v2-steer-", |
| 3316 | }); |
| 3317 | const path = yield* Path.Path; |
| 3318 | const skill = path.join(workspace, ".cursor", "skills", "review"); |
| 3319 | yield* fileSystem.makeDirectory(skill, { recursive: true }); |
| 3320 | yield* fileSystem.writeFileString( |
| 3321 | path.join(skill, "SKILL.md"), |
| 3322 | "# Review\nReview the code.", |
| 3323 | ); |
| 3324 | const userOnlySkill = path.join(workspace, ".cursor", "skills", "grill-me"); |
| 3325 | yield* fileSystem.makeDirectory(userOnlySkill, { recursive: true }); |
| 3326 | yield* fileSystem.writeFileString( |
| 3327 | path.join(userOnlySkill, "SKILL.md"), |
| 3328 | "---\nname: grill-me\ndescription: Grill the plan.\ndisable-model-invocation: true\n---\nAsk one question at a time.", |
| 3329 | ); |
| 3330 | const steered: string[] = []; |
| 3331 | let cancelled = 0; |
| 3332 | let outcome: "complete_delivered" | "revert_to_followup" = "complete_delivered"; |
| 3333 | const finished = yield* Deferred.make<{ |
| 3334 | readonly id: string; |
| 3335 | readonly requestId: string; |
| 3336 | readonly status: "finished" | "cancelled"; |
| 3337 | readonly model: { readonly id: string }; |
| 3338 | readonly durationMs: number; |
| 3339 | }>(); |
| 3340 | const instanceId = ProviderInstanceId.make("cursor"); |
| 3341 | const threadId = ThreadId.make("cursor-steer-thread"); |
| 3342 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 3343 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 3344 | runtimeMode: "full-access", |
| 3345 | interactionMode: "default", |
| 3346 | cwd: workspace, |
| 3347 | }); |
| 3348 | const adapter = yield* makeCursorAdapterV2({ |
| 3349 | instanceId, |
| 3350 | environment: { HOME: workspace }, |
| 3351 | }).pipe( |
| 3352 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 3353 | assertComplete: Effect.void, |
| 3354 | open: () => |
| 3355 | Effect.succeed({ |
| 3356 | agentId: "native-cursor-steer", |
| 3357 | listMessages: Effect.succeed([]), |
| 3358 | close: Effect.void, |
| 3359 | send: () => |
| 3360 | Effect.succeed({ |
| 3361 | agentId: "native-cursor-steer", |
| 3362 | runId: "native-cursor-steer-run", |
| 3363 | wait: Deferred.await(finished), |
| 3364 | cancel: Effect.sync(() => { |
| 3365 | cancelled += 1; |
| 3366 | }).pipe( |
| 3367 | Effect.andThen( |
| 3368 | Deferred.succeed(finished, { |
| 3369 | id: "native-cursor-steer-run", |
| 3370 | requestId: "native-request", |
| 3371 | status: "cancelled" as const, |
| 3372 | model: { id: "composer-2.5" }, |
| 3373 | durationMs: 1, |
| 3374 | }), |
| 3375 | ), |
| 3376 | ), |
| 3377 | steer: (text) => |
| 3378 | Effect.sync(() => { |
| 3379 | steered.push(text); |
| 3380 | return outcome; |
| 3381 | }), |
| 3382 | }), |
| 3383 | }), |
| 3384 | }), |
| 3385 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 3386 | ); |
| 3387 | const runtime = yield* adapter.openSession({ |
| 3388 | threadId, |
| 3389 | providerSessionId: ProviderSessionId.make("cursor-steer-session"), |
| 3390 | modelSelection, |
| 3391 | runtimePolicy, |
| 3392 | }); |
| 3393 | assert.equal( |
| 3394 | runtime.providerSession.capabilities.turns.activeSteeringAcceptsAttachments, |
| 3395 | false, |
| 3396 | ); |
| 3397 | const providerThread = yield* runtime.ensureThread({ |
| 3398 | threadId, |
| 3399 | modelSelection, |
| 3400 | runtimePolicy, |
| 3401 | }); |
| 3402 | const now = yield* DateTime.now; |
| 3403 | const turn = { |
| 3404 | threadId, |
| 3405 | providerThread, |
| 3406 | modelSelection, |
| 3407 | runtimePolicy, |
| 3408 | runId: RunId.make("cursor-steer-run"), |
| 3409 | runOrdinal: 1, |
| 3410 | providerTurnOrdinal: 1, |
| 3411 | attemptId: RunAttemptId.make("cursor-steer-attempt"), |
| 3412 | rootNodeId: NodeId.make("cursor-steer-root"), |
| 3413 | appThread: { |
| 3414 | id: threadId, |
| 3415 | projectId: ProjectId.make("cursor-steer-project"), |
| 3416 | createdBy: "user" as const, |
| 3417 | creationSource: "web" as const, |
| 3418 | title: "Cursor steer", |
| 3419 | providerInstanceId: instanceId, |
| 3420 | modelSelection, |
| 3421 | runtimeMode: "full-access" as const, |
| 3422 | interactionMode: "default" as const, |
| 3423 | branch: null, |
| 3424 | worktreePath: null, |
| 3425 | activeProviderThreadId: providerThread.id, |
| 3426 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 3427 | forkedFrom: null, |
| 3428 | createdAt: now, |
| 3429 | updatedAt: now, |
| 3430 | archivedAt: null, |
| 3431 | settledOverride: null, |
| 3432 | settledAt: null, |
| 3433 | lastVisitedAt: null, |
| 3434 | deletedAt: null, |
| 3435 | }, |
| 3436 | message: { |
| 3437 | messageId: MessageId.make("cursor-steer-message"), |
| 3438 | createdBy: "user" as const, |
| 3439 | creationSource: "web" as const, |
| 3440 | text: "Review the code.", |
| 3441 | attachments: [], |
| 3442 | }, |
| 3443 | }; |
| 3444 | const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ |
| 3445 | driver: CursorAgentSdk.CURSOR_PROVIDER, |
| 3446 | nativeTurnId: "native-cursor-steer-run", |
| 3447 | }); |
| 3448 | yield* runtime.startTurn(turn); |
| 3449 | yield* runtime.steerTurn({ |
| 3450 | threadId, |
| 3451 | runId: turn.runId, |
| 3452 | providerThread, |
| 3453 | providerTurnId, |
| 3454 | message: { |
| 3455 | messageId: MessageId.make("cursor-steer-follow-up"), |
| 3456 | createdBy: "user", |
| 3457 | creationSource: "web", |
| 3458 | text: "$review Look at the tests instead.", |
| 3459 | attachments: [], |
| 3460 | }, |
| 3461 | }); |
| 3462 | assert.deepEqual(steered, ["/review Look at the tests instead."]); |
| 3463 | assert.equal(cancelled, 0); |
| 3464 | yield* runtime.steerTurn({ |
| 3465 | threadId, |
| 3466 | runId: turn.runId, |
| 3467 | providerThread, |
| 3468 | providerTurnId, |
| 3469 | message: { |
| 3470 | messageId: MessageId.make("cursor-steer-user-only-skill"), |
| 3471 | createdBy: "user", |
| 3472 | creationSource: "web", |
| 3473 | text: "$grill-me My plan.", |
| 3474 | attachments: [], |
| 3475 | }, |
| 3476 | }); |
| 3477 | // Cursor hides `disable-model-invocation` skills from the model, so the SDK prompt must carry them. |
| 3478 | assert.include(steered.at(-1), "Ask one question at a time."); |
| 3479 | |
| 3480 | outcome = "revert_to_followup"; |
| 3481 | const declined = yield* runtime |
| 3482 | .steerTurn({ |
| 3483 | threadId, |
| 3484 | runId: turn.runId, |
| 3485 | providerThread, |
| 3486 | providerTurnId, |
| 3487 | message: { |
| 3488 | messageId: MessageId.make("cursor-steer-declined"), |
| 3489 | createdBy: "user", |
| 3490 | creationSource: "web", |
| 3491 | text: "Stop and do this.", |
| 3492 | attachments: [], |
| 3493 | }, |
| 3494 | }) |
| 3495 | .pipe(Effect.exit); |
| 3496 | if (!Exit.isFailure(declined)) return yield* Effect.die("Expected a declined steer"); |
| 3497 | assert.equal(steered.at(-1), "Stop and do this."); |
| 3498 | assert.equal(cancelled, 0); |
| 3499 | const declinedError = Cause.squash(declined.cause); |
| 3500 | assert.instanceOf(declinedError, ProviderAdapter.ProviderAdapterSteerDeclinedError); |
| 3501 | yield* runtime.interruptTurn({ |
| 3502 | providerThread, |
| 3503 | providerTurnId, |
| 3504 | }); |
| 3505 | assert.equal(cancelled, 1); |
| 3506 | }).pipe( |
| 3507 | Effect.scoped, |
| 3508 | Effect.provide( |
| 3509 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 3510 | ), |
| 3511 | ), |
| 3512 | ); |
| 3513 | |
| 3514 | it.effect("reopens a fresh session when a cached worker session is no longer alive", () => |
| 3515 | Effect.gen(function* () { |
| 3516 | const fileSystem = yield* FileSystem.FileSystem; |
| 3517 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ |
| 3518 | prefix: "t3code-cursor-dead-worker-", |
| 3519 | }); |
| 3520 | const instanceId = ProviderInstanceId.make("cursor"); |
| 3521 | const threadId = ThreadId.make("cursor-dead-worker-thread"); |
| 3522 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 3523 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 3524 | runtimeMode: "full-access", |
| 3525 | interactionMode: "default", |
| 3526 | cwd: workspace, |
| 3527 | }); |
| 3528 | |
| 3529 | let firstAlive = true; |
| 3530 | let firstClosed = 0; |
| 3531 | const opens: Array<{ readonly operation: string; readonly agentId?: string }> = []; |
| 3532 | const sends: Array<number> = []; |
| 3533 | |
| 3534 | const adapter = yield* makeCursorAdapterV2({ |
| 3535 | instanceId, |
| 3536 | environment: { HOME: workspace }, |
| 3537 | }).pipe( |
| 3538 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 3539 | assertComplete: Effect.void, |
| 3540 | open: (input) => { |
| 3541 | const sessionNumber = opens.length + 1; |
| 3542 | opens.push({ |
| 3543 | operation: input.operation, |
| 3544 | ...(input.agentId === undefined ? {} : { agentId: input.agentId }), |
| 3545 | }); |
| 3546 | return Effect.succeed({ |
| 3547 | agentId: "native-cursor-reopen", |
| 3548 | isAlive: () => (sessionNumber === 1 ? firstAlive : true), |
| 3549 | listMessages: Effect.succeed([]), |
| 3550 | close: Effect.sync(() => { |
| 3551 | if (sessionNumber === 1) firstClosed += 1; |
| 3552 | }), |
| 3553 | send: () => { |
| 3554 | sends.push(sessionNumber); |
| 3555 | return Effect.succeed({ |
| 3556 | agentId: "native-cursor-reopen", |
| 3557 | runId: `run-${sessionNumber}`, |
| 3558 | wait: Effect.succeed({ |
| 3559 | id: `run-${sessionNumber}`, |
| 3560 | requestId: `req-${sessionNumber}`, |
| 3561 | status: "finished" as const, |
| 3562 | result: "ok", |
| 3563 | model: { id: "composer-2.5" }, |
| 3564 | durationMs: 1, |
| 3565 | }), |
| 3566 | cancel: Effect.void, |
| 3567 | }); |
| 3568 | }, |
| 3569 | }); |
| 3570 | }, |
| 3571 | }), |
| 3572 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 3573 | ); |
| 3574 | |
| 3575 | const runtime = yield* adapter.openSession({ |
| 3576 | threadId, |
| 3577 | providerSessionId: ProviderSessionId.make("cursor-dead-worker-session"), |
| 3578 | modelSelection, |
| 3579 | runtimePolicy, |
| 3580 | }); |
| 3581 | const providerThread = yield* runtime.ensureThread({ |
| 3582 | threadId, |
| 3583 | modelSelection, |
| 3584 | runtimePolicy, |
| 3585 | }); |
| 3586 | assert.deepEqual(opens, [{ operation: "create" }]); |
| 3587 | |
| 3588 | // Simulate the first worker terminating after ensureThread. |
| 3589 | firstAlive = false; |
| 3590 | const now = yield* DateTime.now; |
| 3591 | yield* runtime.startTurn({ |
| 3592 | threadId, |
| 3593 | providerThread, |
| 3594 | modelSelection, |
| 3595 | runtimePolicy, |
| 3596 | runId: RunId.make("cursor-dead-worker-run"), |
| 3597 | runOrdinal: 1, |
| 3598 | providerTurnOrdinal: 1, |
| 3599 | attemptId: RunAttemptId.make("cursor-dead-worker-attempt"), |
| 3600 | rootNodeId: NodeId.make("cursor-dead-worker-root"), |
| 3601 | appThread: { |
| 3602 | id: threadId, |
| 3603 | projectId: ProjectId.make("cursor-dead-worker-project"), |
| 3604 | createdBy: "user", |
| 3605 | creationSource: "web", |
| 3606 | title: "Dead worker recovery", |
| 3607 | providerInstanceId: instanceId, |
| 3608 | modelSelection, |
| 3609 | runtimeMode: "full-access", |
| 3610 | interactionMode: "default", |
| 3611 | branch: null, |
| 3612 | worktreePath: null, |
| 3613 | activeProviderThreadId: providerThread.id, |
| 3614 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 3615 | forkedFrom: null, |
| 3616 | createdAt: now, |
| 3617 | updatedAt: now, |
| 3618 | archivedAt: null, |
| 3619 | settledOverride: null, |
| 3620 | settledAt: null, |
| 3621 | lastVisitedAt: null, |
| 3622 | deletedAt: null, |
| 3623 | }, |
| 3624 | message: { |
| 3625 | messageId: MessageId.make("cursor-dead-worker-message"), |
| 3626 | createdBy: "user", |
| 3627 | creationSource: "web", |
| 3628 | text: "Continue on a fresh worker.", |
| 3629 | attachments: [], |
| 3630 | }, |
| 3631 | }); |
| 3632 | const events = yield* runtime.events.pipe( |
| 3633 | Stream.takeUntil((event) => event.type === "turn.terminal"), |
| 3634 | Stream.runCollect, |
| 3635 | ); |
| 3636 | assert.equal(events.find((event) => event.type === "turn.terminal")?.status, "completed"); |
| 3637 | assert.equal(firstClosed, 1); |
| 3638 | assert.deepEqual(opens, [ |
| 3639 | { operation: "create" }, |
| 3640 | { operation: "resume", agentId: "native-cursor-reopen" }, |
| 3641 | ]); |
| 3642 | assert.deepEqual(sends, [2]); |
| 3643 | }).pipe( |
| 3644 | Effect.scoped, |
| 3645 | Effect.provide( |
| 3646 | Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), |
| 3647 | ), |
| 3648 | ), |
| 3649 | ); |
| 3650 | |
| 3651 | it("preserves failed nested read calls when Cursor omits their path", () => { |
| 3652 | assert.deepEqual( |
| 3653 | nestedToolCallFromEnvelope({ |
| 3654 | toolCallId: "tool:failed-read", |
| 3655 | readToolCall: { |
| 3656 | args: {}, |
| 3657 | result: { error: "File path was not provided." }, |
| 3658 | }, |
| 3659 | }), |
| 3660 | { |
| 3661 | callId: "tool:failed-read", |
| 3662 | toolCall: { |
| 3663 | type: "read", |
| 3664 | args: { path: "<unknown path>" }, |
| 3665 | result: { |
| 3666 | status: "error", |
| 3667 | error: "File path was not provided.", |
| 3668 | }, |
| 3669 | }, |
| 3670 | }, |
| 3671 | ); |
| 3672 | }); |
| 3673 | }); |
| 3674 | |
| 3675 | type CursorTaskUpdate = Extract< |
| 3676 | InteractionUpdate, |
| 3677 | { readonly type: "tool-call-delta" } |
| 3678 | >["taskUpdate"]; |
| 3679 | |
| 3680 | // Runs one Cursor turn whose only tool is a Task that streams `taskUpdates`, then completes with |
| 3681 | // `conversationSteps` as the saved transcript. |
| 3682 | const runCursorTaskTurn = Effect.fnUntraced(function* ( |
| 3683 | taskUpdates: ReadonlyArray<CursorTaskUpdate>, |
| 3684 | conversationSteps: ReadonlyArray<unknown>, |
| 3685 | ) { |
| 3686 | const fileSystem = yield* FileSystem.FileSystem; |
| 3687 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-task-" }); |
| 3688 | const instanceId = ProviderInstanceId.make("cursor"); |
| 3689 | const threadId = ThreadId.make("cursor-task-thread"); |
| 3690 | const modelSelection = { instanceId, model: "composer-2.5" }; |
| 3691 | const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ |
| 3692 | runtimeMode: "full-access", |
| 3693 | interactionMode: "default", |
| 3694 | cwd: workspace, |
| 3695 | }); |
| 3696 | const args = { |
| 3697 | description: "Explore", |
| 3698 | prompt: "Read package.json.", |
| 3699 | subagentType: { kind: "unspecified" as const }, |
| 3700 | agentId: "cursor-task-agent", |
| 3701 | mode: "unspecified" as const, |
| 3702 | }; |
| 3703 | const adapter = yield* makeCursorAdapterV2({ |
| 3704 | instanceId, |
| 3705 | environment: { HOME: workspace }, |
| 3706 | }).pipe( |
| 3707 | Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { |
| 3708 | assertComplete: Effect.void, |
| 3709 | open: () => |
| 3710 | Effect.succeed({ |
| 3711 | agentId: "native-cursor-task", |
| 3712 | listMessages: Effect.succeed([]), |
| 3713 | close: Effect.void, |
| 3714 | send: (input) => |
| 3715 | Effect.gen(function* () { |
| 3716 | yield* input.onDelta!({ |
| 3717 | type: "tool-call-started", |
| 3718 | modelCallId: "model-call", |
| 3719 | callId: "task-call", |
| 3720 | toolCall: { type: "task", args }, |
| 3721 | }); |
| 3722 | for (const taskUpdate of taskUpdates) { |
| 3723 | yield* input.onDelta!({ |
| 3724 | type: "tool-call-delta", |
| 3725 | modelCallId: "model-call", |
| 3726 | callId: "task-call", |
| 3727 | taskUpdate, |
| 3728 | }); |
| 3729 | } |
| 3730 | yield* input.onDelta!({ |
| 3731 | type: "tool-call-completed", |
| 3732 | modelCallId: "model-call", |
| 3733 | callId: "task-call", |
| 3734 | toolCall: { |
| 3735 | type: "task", |
| 3736 | args, |
| 3737 | result: { |
| 3738 | status: "success", |
| 3739 | value: { |
| 3740 | conversationSteps: [...conversationSteps], |
| 3741 | isBackground: false, |
| 3742 | backgroundReason: "unspecified", |
| 3743 | }, |
| 3744 | }, |
| 3745 | }, |
| 3746 | }); |
| 3747 | return { |
| 3748 | agentId: "native-cursor-task", |
| 3749 | runId: "native-cursor-run", |
| 3750 | wait: Effect.succeed({ |
| 3751 | id: "native-cursor-run", |
| 3752 | requestId: "native-request", |
| 3753 | status: "finished" as const, |
| 3754 | model: { id: "composer-2.5" }, |
| 3755 | durationMs: 1, |
| 3756 | }), |
| 3757 | cancel: Effect.void, |
| 3758 | }; |
| 3759 | }).pipe(Effect.orDie), |
| 3760 | }), |
| 3761 | }), |
| 3762 | Effect.provide(TestProviderHost.layer({ cwd: workspace })), |
| 3763 | ); |
| 3764 | const runtime = yield* adapter.openSession({ |
| 3765 | threadId, |
| 3766 | providerSessionId: ProviderSessionId.make("cursor-task-session"), |
| 3767 | modelSelection, |
| 3768 | runtimePolicy, |
| 3769 | }); |
| 3770 | const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); |
| 3771 | const now = yield* DateTime.now; |
| 3772 | yield* runtime.startTurn({ |
| 3773 | threadId, |
| 3774 | providerThread, |
| 3775 | modelSelection, |
| 3776 | runtimePolicy, |
| 3777 | runId: RunId.make("cursor-task-run"), |
| 3778 | runOrdinal: 1, |
| 3779 | providerTurnOrdinal: 1, |
| 3780 | attemptId: RunAttemptId.make("cursor-task-attempt"), |
| 3781 | rootNodeId: NodeId.make("cursor-task-root"), |
| 3782 | appThread: { |
| 3783 | id: threadId, |
| 3784 | projectId: ProjectId.make("cursor-task-project"), |
| 3785 | createdBy: "user", |
| 3786 | creationSource: "web", |
| 3787 | title: "Cursor subagent", |
| 3788 | providerInstanceId: instanceId, |
| 3789 | modelSelection, |
| 3790 | runtimeMode: "full-access", |
| 3791 | interactionMode: "default", |
| 3792 | branch: null, |
| 3793 | worktreePath: null, |
| 3794 | activeProviderThreadId: providerThread.id, |
| 3795 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 3796 | forkedFrom: null, |
| 3797 | createdAt: now, |
| 3798 | updatedAt: now, |
| 3799 | archivedAt: null, |
| 3800 | settledOverride: null, |
| 3801 | settledAt: null, |
| 3802 | lastVisitedAt: null, |
| 3803 | deletedAt: null, |
| 3804 | }, |
| 3805 | message: { |
| 3806 | messageId: MessageId.make("cursor-task-message"), |
| 3807 | createdBy: "user", |
| 3808 | creationSource: "web", |
| 3809 | text: "Spawn a subagent.", |
| 3810 | attachments: [], |
| 3811 | }, |
| 3812 | }); |
| 3813 | const events = yield* runtime.events.pipe( |
| 3814 | Stream.takeUntil((event) => event.type === "turn.terminal"), |
| 3815 | Stream.runCollect, |
| 3816 | ); |
| 3817 | assert.equal(events.find((event) => event.type === "turn.terminal")?.status, "completed"); |
| 3818 | const childThreadId = events.findLast((event) => event.type === "subagent.updated")?.subagent |
| 3819 | .childThreadId; |
| 3820 | assert.isDefined(childThreadId); |
| 3821 | return { events, childThreadId }; |
| 3822 | }); |
| 3823 | |
| 3824 | const scopedProcessEnv = (values: Record<string, string>) => |
| 3825 | Effect.acquireRelease( |
| 3826 | Effect.sync(() => { |
| 3827 | for (const [key, value] of Object.entries(values)) vi.stubEnv(key, value); |
| 3828 | }), |
| 3829 | () => Effect.sync(() => vi.unstubAllEnvs()), |
| 3830 | ); |
| 3831 | |
| 3832 | // Loopback stand-in for Cursor's backend: it asks the local SDK runtime for its request |
| 3833 | // context over RunSSE and decodes the RequestContext the SDK appends back (agent.v1 protos). |
| 3834 | const fakeCursorBackend = Effect.gen(function* () { |
| 3835 | const requestContext = yield* Deferred.make<{ |
| 3836 | readonly commitAttributionMessage: string | undefined; |
| 3837 | readonly prAttributionMessage: string | undefined; |
| 3838 | }>(); |
| 3839 | const requestContextExec = protoField( |
| 3840 | 2, |
| 3841 | Buffer.concat([Buffer.from([0x08, 0x01]), protoField(15, Buffer.from("ctx")), protoField(10)]), |
| 3842 | ); |
| 3843 | const models = ["composer-2"]; |
| 3844 | const runFrame = Buffer.alloc(5 + requestContextExec.length); |
| 3845 | runFrame.writeUInt32BE(requestContextExec.length, 1); |
| 3846 | requestContextExec.copy(runFrame, 5); |
| 3847 | const server = NodeHttp.createServer((request, response) => { |
| 3848 | const chunks: Array<Buffer> = []; |
| 3849 | request.on("data", (chunk: Buffer) => chunks.push(chunk)); |
| 3850 | request.on("end", () => { |
| 3851 | switch (request.url) { |
| 3852 | case "/auth/exchange_user_api_key": |
| 3853 | response.setHeader("content-type", "application/json"); |
| 3854 | response.end(JSON.stringify({ accessToken: "synthetic-access-token" })); |
| 3855 | return; |
| 3856 | case "/v1/models": |
| 3857 | response.setHeader("content-type", "application/json"); |
| 3858 | response.end(JSON.stringify({ items: models.map((id) => ({ id })) })); |
| 3859 | return; |
| 3860 | case "/agent.v1.AgentService/RunSSE": |
| 3861 | response.writeHead(200, { "content-type": "application/connect+proto" }); |
| 3862 | response.write(runFrame); |
| 3863 | return; |
| 3864 | case "/aiserver.v1.BidiService/BidiAppend": { |
| 3865 | const appended = protoGet(Buffer.concat(chunks), 1); |
| 3866 | const clientMessage = Buffer.from(appended?.toString() ?? "", "hex"); |
| 3867 | const success = protoPath(clientMessage, [2, 10, 1]); |
| 3868 | if (success !== undefined) { |
| 3869 | const context = protoGet(success, 1); |
| 3870 | Deferred.doneUnsafe( |
| 3871 | requestContext, |
| 3872 | context === undefined |
| 3873 | ? Effect.die(new Error("RequestContextSuccess carried no RequestContext")) |
| 3874 | : Effect.succeed({ |
| 3875 | commitAttributionMessage: protoGet(context, 26)?.toString(), |
| 3876 | prAttributionMessage: protoGet(context, 27)?.toString(), |
| 3877 | }), |
| 3878 | ); |
| 3879 | } |
| 3880 | response.setHeader("content-type", "application/proto"); |
| 3881 | response.end(); |
| 3882 | return; |
| 3883 | } |
| 3884 | default: |
| 3885 | response.statusCode = 404; |
| 3886 | response.end(); |
| 3887 | } |
| 3888 | }); |
| 3889 | }); |
| 3890 | yield* Effect.acquireRelease( |
| 3891 | Effect.callback<void>((resume) => { |
| 3892 | server.listen(Number(new URL(cursorBackendUrl).port), "127.0.0.1", () => resume(Effect.void)); |
| 3893 | }), |
| 3894 | () => |
| 3895 | Effect.callback<void>((resume) => { |
| 3896 | server.closeAllConnections(); |
| 3897 | server.close(() => resume(Effect.void)); |
| 3898 | }), |
| 3899 | ); |
| 3900 | return { requestContext, models }; |
| 3901 | }); |
| 3902 | |
| 3903 | function protoVarint(value: number): Buffer { |
| 3904 | const bytes: Array<number> = []; |
| 3905 | while (value > 0x7f) { |
| 3906 | bytes.push((value & 0x7f) | 0x80); |
| 3907 | value >>>= 7; |
| 3908 | } |
| 3909 | bytes.push(value); |
| 3910 | return Buffer.from(bytes); |
| 3911 | } |
| 3912 | |
| 3913 | function protoField(fieldNumber: number, value: Buffer = Buffer.alloc(0)): Buffer { |
| 3914 | return Buffer.concat([protoVarint((fieldNumber << 3) | 2), protoVarint(value.length), value]); |
| 3915 | } |
| 3916 | |
| 3917 | function protoGet(message: Buffer, fieldNumber: number): Buffer | undefined { |
| 3918 | let offset = 0; |
| 3919 | const readVarint = () => { |
| 3920 | let value = 0; |
| 3921 | let shift = 0; |
| 3922 | let byte: number; |
| 3923 | do { |
| 3924 | byte = message[offset++] ?? 0; |
| 3925 | value += (byte & 0x7f) * 2 ** shift; |
| 3926 | shift += 7; |
| 3927 | } while (byte & 0x80); |
| 3928 | return value; |
| 3929 | }; |
| 3930 | while (offset < message.length) { |
| 3931 | const key = readVarint(); |
| 3932 | const wireType = key & 7; |
| 3933 | if (wireType === 0) { |
| 3934 | readVarint(); |
| 3935 | } else if (wireType === 1) { |
| 3936 | offset += 8; |
| 3937 | } else if (wireType === 5) { |
| 3938 | offset += 4; |
| 3939 | } else { |
| 3940 | const length = readVarint(); |
| 3941 | if (Math.floor(key / 8) === fieldNumber) return message.subarray(offset, offset + length); |
| 3942 | offset += length; |
| 3943 | } |
| 3944 | } |
| 3945 | return undefined; |
| 3946 | } |
| 3947 | |
| 3948 | function protoPath(message: Buffer, fieldNumbers: ReadonlyArray<number>): Buffer | undefined { |
| 3949 | let current: Buffer | undefined = message; |
| 3950 | for (const fieldNumber of fieldNumbers) { |
| 3951 | current = current === undefined ? undefined : protoGet(current, fieldNumber); |
| 3952 | } |
| 3953 | return current; |
| 3954 | } |