The best way to control Claude Code, Codex and more from any computer or phone

main
ts 3,665 lines 144 KB
Raw
1 import type {
2 AgentMessage,
3 AgentOptions,
4 InteractionUpdate,
5 McpServerConfig,
6 RunResult,
7 SDKModel,
8 SDKUserMessage,
9 SettingSource,
10 ToolCall,
11 } from "@cursor/sdk";
12 import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/toolActivity";
13 import * as HostProcess from "@t3tools/shared/HostProcess";
14 import {
15 isOrchestrationV2WorkActive,
16 defaultInstanceIdForDriver,
17 type ChatAttachment,
18 type ModelSelection,
19 type OrchestrationV2ConversationMessage,
20 type OrchestrationV2ExecutionNode,
21 type OrchestrationV2PlanArtifact,
22 type OrchestrationV2PlanStep,
23 type OrchestrationV2ProviderCapabilities,
24 type OrchestrationV2ProviderFailure,
25 type OrchestrationV2ProviderSession,
26 type OrchestrationV2ProviderThread,
27 type OrchestrationV2ProviderTurn,
28 type OrchestrationV2Subagent,
29 type OrchestrationV2TurnItem,
30 type ProviderInstanceId,
31 type ServerProviderModel,
32 type ServerProviderSkill,
33 type ThreadId,
34 } from "@t3tools/contracts";
35 import * as DateTime from "effect/DateTime";
36 import * as Deferred from "effect/Deferred";
37 import * as Effect from "effect/Effect";
38 import * as FileSystem from "effect/FileSystem";
39 import * as Option from "effect/Option";
40 import * as Path from "effect/Path";
41 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
42 import * as Queue from "effect/Queue";
43 import * as Ref from "effect/Ref";
44 import * as Schema from "effect/Schema";
45 import * as Stream from "effect/Stream";
46
47 import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
48 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
49 import { backgroundWorkNotification } from "@t3tools/provider-core/server/notification";
50 import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation";
51 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
52 import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
53 import { CursorTransportFailure } from "./transportFailure.ts";
54 import { cursorContextWindowTokens, cursorSdkModelSelection } from "./sdkModel.ts";
55 import {
56 appendCursorInvokedSkills,
57 cursorSlashSkillNames,
58 discoverCursorSkills,
59 hasCursorSkillMention,
60 rewriteCursorSkillMentions,
61 } from "./skills.ts";
62 import { cursorWorkspaceMcpServers } from "./workspaceMcpServers.ts";
63 import { t3OrchestrationPrompt } from "@t3tools/provider-core/server/orchestrationInstructions";
64 import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
65 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
66 import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
67 import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
68 import {
69 isProviderNativeImageAttachment,
70 providerMessageTextWithAttachmentPaths,
71 } from "@t3tools/provider-core/server/attachmentPrompt";
72 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
73 import {
74 makeSubagentChildThread,
75 makeSubagentConversationArtifacts,
76 subagentThreadTitle,
77 } from "@t3tools/provider-core/server/subagentProjection";
78 import * as CursorAgentSdk from "./CursorAgentSdk.ts";
79 import { isCursorSdkError } from "./sdk.ts";
80 export { cursorSdkModelSelection } from "./sdkModel.ts";
81
82 const CURSOR_DRIVER_KIND = CursorAgentSdk.CURSOR_PROVIDER;
83 export const CURSOR_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CURSOR_DRIVER_KIND);
84
85 export const CursorProviderCapabilitiesV2 = {
86 sessions: {
87 supportsMultipleProviderThreadsPerSession: false,
88 supportsModelSwitchInSession: true,
89 supportsProviderSwitchingViaHandoff: true,
90 supportsRuntimeModeSwitchInSession: false,
91 pendingRequestsSurviveRestart: false,
92 },
93 threads: {
94 canCreateEmptyThread: true,
95 canReadThreadSnapshot: true,
96 canRollbackThread: true,
97 canForkThread: false,
98 canForkFromTurn: false,
99 canForkFromSubagentThread: false,
100 exposesNativeThreadId: true,
101 },
102 turns: {
103 exposesNativeTurnId: true,
104 emitsTurnStarted: true,
105 emitsTurnCompleted: true,
106 supportsInterrupt: true,
107 supportsNativeResume: true,
108 supportsActiveSteering: true,
109 // A steer can move a foreground subagent to the background. Mailbox wakes
110 // stay queued so a notification does not cut into the live turn.
111 activeSteeringInterruptsTools: true,
112 activeSteeringAcceptsAttachments: false,
113 supportsSteeringByInterruptRestart: true,
114 supportsQueuedMessages: true,
115 terminalStatusQuality: "strong",
116 },
117 streaming: {
118 streamsAssistantText: true,
119 streamsReasoning: true,
120 streamsToolOutput: true,
121 streamsPlanText: true,
122 emitsMessageCompleted: true,
123 },
124 tools: {
125 exposesToolItemIds: true,
126 emitsToolStarted: true,
127 emitsToolCompleted: true,
128 emitsToolOutput: true,
129 supportsMcpTools: true,
130 supportsDynamicToolCallbacks: false,
131 supportsBackgroundWait: true,
132 },
133 approvals: {
134 supportsCommandApproval: false,
135 supportsFileReadApproval: false,
136 supportsFileChangeApproval: false,
137 supportsApplyPatchApproval: false,
138 approvalsHaveNativeRequestIds: false,
139 approvalCallbacksAreLiveOnly: false,
140 approvalsCanOriginateFromSubagents: false,
141 },
142 planning: {
143 emitsPlanUpdated: true,
144 emitsTodoList: true,
145 emitsProposedPlan: true,
146 supportsStructuredQuestions: false,
147 planDeltasHaveItemIds: true,
148 },
149 subagents: {
150 supportsSubagents: true,
151 exposesSubagentThreadIds: false,
152 emitsSubagentLifecycle: true,
153 canWaitForSubagents: true,
154 canCloseSubagents: false,
155 canForkSubagentThread: false,
156 },
157 context: {
158 acceptsSystemContext: false,
159 acceptsDeveloperContext: false,
160 acceptsSyntheticUserContext: true,
161 canGenerateSummaries: true,
162 canConsumeHandoffSummaries: true,
163 supportsDeltaHandoff: true,
164 supportsFullThreadHandoff: true,
165 maxRecommendedHandoffChars: null,
166 },
167 checkpointing: {
168 appCanCheckpointFilesystem: true,
169 supportsNestedCheckpointScopes: true,
170 providerCanRollbackConversation: true,
171 providerRollbackReturnsSnapshot: true,
172 providerCanReadConversationSnapshot: true,
173 },
174 identity: {
175 nativeThreadIds: "strong",
176 nativeTurnIds: "strong",
177 nativeItemIds: "weak",
178 nativeRequestIds: "none",
179 },
180 runtimePolicy: {
181 enforcement: "native",
182 },
183 } satisfies OrchestrationV2ProviderCapabilities;
184
185 export interface CursorRuntimeAgentPolicy {
186 readonly autoReview: boolean;
187 readonly sandboxEnabled: boolean;
188 }
189
190 export function cursorRuntimeAgentPolicy(
191 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
192 platform: NodeJS.Platform,
193 ): CursorRuntimeAgentPolicy {
194 const sandboxPolicyType =
195 typeof runtimePolicy.sandboxPolicy === "object" &&
196 runtimePolicy.sandboxPolicy !== null &&
197 "type" in runtimePolicy.sandboxPolicy &&
198 typeof runtimePolicy.sandboxPolicy.type === "string"
199 ? runtimePolicy.sandboxPolicy.type
200 : undefined;
201 const autoReview =
202 runtimePolicy.approvalPolicy === undefined
203 ? runtimePolicy.runtimeMode === "approval-required" || runtimePolicy.runtimeMode === "auto"
204 : runtimePolicy.approvalPolicy !== "never";
205 return {
206 autoReview,
207 // The Windows SDK has no filesystem sandbox; omit the default only when
208 // Auto-review still gates execution. Explicit policies remain authoritative.
209 sandboxEnabled:
210 runtimePolicy.sandboxPolicy === undefined
211 ? runtimePolicy.runtimeMode !== "full-access" && !(platform === "win32" && autoReview)
212 : sandboxPolicyType !== "dangerFullAccess",
213 };
214 }
215
216 export function cursorMcpServers(
217 session: McpProviderSession.McpProviderSessionConfig | undefined,
218 ): Record<string, McpServerConfig> | undefined {
219 if (session === undefined) {
220 return undefined;
221 }
222 return {
223 "t3-code": {
224 type: "http",
225 url: session.endpoint,
226 headers: {
227 Authorization: session.authorizationHeader,
228 },
229 },
230 };
231 }
232
233 function providerSession(input: {
234 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
235 readonly providerInstanceId: ProviderInstanceId;
236 readonly cwd: string | null;
237 readonly model: string;
238 readonly now: DateTime.Utc;
239 }): OrchestrationV2ProviderSession {
240 return {
241 id: input.providerSessionId,
242 driver: CursorAgentSdk.CURSOR_PROVIDER,
243 providerInstanceId: input.providerInstanceId,
244 status: "ready",
245 cwd: input.cwd ?? process.cwd(),
246 model: input.model,
247 capabilities: CursorProviderCapabilitiesV2,
248 createdAt: input.now,
249 updatedAt: input.now,
250 lastError: null,
251 };
252 }
253
254 function makeProviderThread(input: {
255 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
256 readonly providerInstanceId: ProviderInstanceId;
257 readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"];
258 readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
259 readonly nativeThreadId: string;
260 readonly storeCwd: string;
261 readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"];
262 readonly forkedFrom?: OrchestrationV2ProviderThread["forkedFrom"];
263 readonly now: DateTime.Utc;
264 }): OrchestrationV2ProviderThread {
265 return {
266 id: input.idAllocator.derive.providerThread({
267 driver: CursorAgentSdk.CURSOR_PROVIDER,
268 nativeThreadId: input.nativeThreadId,
269 }),
270 driver: CursorAgentSdk.CURSOR_PROVIDER,
271 providerInstanceId: input.providerInstanceId,
272 providerSessionId: input.providerSessionId,
273 appThreadId: input.appThreadId,
274 ownerNodeId: input.ownerNodeId ?? null,
275 nativeThreadRef: {
276 driver: CursorAgentSdk.CURSOR_PROVIDER,
277 nativeId: input.nativeThreadId,
278 strength: "strong",
279 },
280 nativeConversationHeadRef: null,
281 nativeMetadata: { cursorStoreCwd: input.storeCwd },
282 status: "idle",
283 firstRunOrdinal: null,
284 lastRunOrdinal: null,
285 handoffIds: [],
286 forkedFrom: input.forkedFrom ?? null,
287 createdAt: input.now,
288 updatedAt: input.now,
289 };
290 }
291
292 function nativeThreadId(providerThread: OrchestrationV2ProviderThread): string {
293 const id = providerThread.nativeThreadRef?.nativeId;
294 if (id === null || id === undefined) {
295 throw new ProviderAdapter.ProviderAdapterProtocolError({
296 driver: CursorAgentSdk.CURSOR_PROVIDER,
297 detail: `Provider thread ${providerThread.id} is missing its Cursor agent id.`,
298 });
299 }
300 return id;
301 }
302
303 /** The SDK loads no CLI settings unless `settingSources` is supplied. */
304 const CURSOR_AGENT_SETTING_SOURCES = [
305 "project",
306 "user",
307 "team",
308 "mdm",
309 "plugins",
310 ] as const satisfies ReadonlyArray<SettingSource>;
311
312 export function makeCursorAgentOptions(input: {
313 readonly apiKey?: string;
314 readonly modelSelection: ModelSelection;
315 readonly models?: ReadonlyArray<ServerProviderModel>;
316 readonly sdkModels?: ReadonlyArray<SDKModel>;
317 readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
318 readonly threadId: ThreadId;
319 readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined;
320 readonly platform: NodeJS.Platform;
321 }): AgentOptions {
322 const policy = cursorRuntimeAgentPolicy(input.runtimePolicy, input.platform);
323 const mcpServers = cursorMcpServers(input.mcpSession);
324 return {
325 model: cursorSdkModelSelection(input.modelSelection, input.models, input.sdkModels),
326 name: `T3 Code ${input.threadId}`,
327 mode: input.runtimePolicy.interactionMode === "plan" ? "plan" : "agent",
328 ...(input.apiKey === undefined ? {} : { apiKey: input.apiKey }),
329 local: {
330 ...(input.runtimePolicy.cwd === null ? {} : { cwd: input.runtimePolicy.cwd }),
331 autoReview: policy.autoReview,
332 settingSources:
333 input.runtimePolicy.runtimeMode === "full-access" &&
334 !policy.autoReview &&
335 !policy.sandboxEnabled
336 ? [...CURSOR_AGENT_SETTING_SOURCES]
337 : CURSOR_AGENT_SETTING_SOURCES.filter((source) => source !== "project"),
338 sandboxOptions: {
339 enabled: policy.sandboxEnabled,
340 },
341 enableAgentRetries: true,
342 },
343 ...(mcpServers === undefined ? {} : { mcpServers }),
344 };
345 }
346
347 class CursorModelUnavailableError extends Schema.TaggedError<CursorModelUnavailableError>()(
348 "CursorModelUnavailableError",
349 {
350 model: Schema.String,
351 cause: Schema.Defect(),
352 },
353 ) {
354 override get message(): string {
355 return `Cursor cannot run the model "${this.model}". Cursor only runs models from your Cursor account. Choose one of those, or use OpenCode for OpenRouter and other API-key models.`;
356 }
357 }
358
359 // Uncoded SDK model rejections are identifiable only by message prefix.
360 const classifyCursorModelRejection =
361 (modelSelection: ModelSelection) => (error: CursorAgentSdk.CursorAgentSdkRunnerError) =>
362 isCursorSdkError(error.cause, "ConfigurationError") &&
363 error.cause.message.startsWith("Cannot use this model:")
364 ? new CursorModelUnavailableError({ model: modelSelection.model, cause: error.cause })
365 : error;
366
367 function stableJson(value: unknown): string {
368 try {
369 return JSON.stringify(value, null, 2);
370 } catch {
371 return String(value);
372 }
373 }
374
375 function unknownRecord(value: unknown): Record<string, unknown> | undefined {
376 return typeof value === "object" && value !== null && !Array.isArray(value)
377 ? (value as Record<string, unknown>)
378 : undefined;
379 }
380
381 function nestedString(value: unknown, keys: ReadonlyArray<string>): string | undefined {
382 let current: unknown = value;
383 for (const key of keys) {
384 current = unknownRecord(current)?.[key];
385 }
386 return typeof current === "string" ? current : undefined;
387 }
388
389 function cursorToolFailed(toolCall: ToolCall): boolean {
390 if (toolCall.result?.status === "error") {
391 return true;
392 }
393 // The SDK reports a shell command that exits non-zero as a success.
394 if (toolCall.type === "shell" && toolCall.result?.status === "success") {
395 return toolCall.result.value.exitCode !== 0;
396 }
397 return toolCall.type === "mcp" && toolCall.result?.status === "success"
398 ? toolCall.result.value.isError
399 : false;
400 }
401
402 function cursorToolOutput(toolCall: ToolCall): unknown {
403 const result = toolCall.result;
404 if (result === undefined) {
405 return undefined;
406 }
407 if (toolCall.type === "mcp" && toolCall.result?.status === "success") {
408 return {
409 ...toolCall.result.value,
410 content: toolCall.result.value.content.flatMap((part) => [
411 ...(part.text === undefined ? [] : [{ type: "text", text: part.text.text }]),
412 ...(part.image === undefined
413 ? []
414 : [{ type: "image", mimeType: part.image.mimeType, data: part.image.data }]),
415 ]),
416 };
417 }
418 return result.status === "success" ? result.value : result.error;
419 }
420
421 function cursorToolOutputText(toolCall: ToolCall): string {
422 if (toolCall.type === "shell" && toolCall.result?.status === "success") {
423 return [toolCall.result.value.stdout, toolCall.result.value.stderr]
424 .filter((part) => part.length > 0)
425 .join("\n");
426 }
427 if (toolCall.type === "mcp" && toolCall.result?.status === "success") {
428 return toolCall.result.value.content
429 .flatMap((part) => (part.text === undefined ? [] : [part.text.text]))
430 .join("\n");
431 }
432 const output = cursorToolOutput(toolCall);
433 if (output === undefined) {
434 return "";
435 }
436 return typeof output === "string" ? output : stableJson(output);
437 }
438
439 function cursorToolName(toolCall: ToolCall): string {
440 if (toolCall.type !== "mcp") {
441 return toolCall.type;
442 }
443 const provider = toolCall.args.providerIdentifier ?? "mcp";
444 const tool = toolCall.args.toolName ?? "unknown";
445 return `mcp__${provider}__${tool}`;
446 }
447
448 function cursorToolFileName(toolCall: ToolCall): string {
449 switch (toolCall.type) {
450 case "write":
451 case "delete":
452 case "read":
453 case "edit":
454 case "ls":
455 return toolCall.args.path;
456 case "generateImage":
457 return toolCall.args.filePath ?? "generated-image";
458 default:
459 return cursorToolName(toolCall);
460 }
461 }
462
463 function cursorToolSearchPattern(toolCall: ToolCall): string | undefined {
464 switch (toolCall.type) {
465 case "glob":
466 return toolCall.args.globPattern;
467 case "grep":
468 return toolCall.args.pattern;
469 case "semSearch":
470 return toolCall.args.query;
471 case "ls":
472 return toolCall.args.path;
473 case "readLints":
474 return toolCall.args.paths.join(", ");
475 default:
476 return undefined;
477 }
478 }
479
480 type CursorLsDirectoryNode = Extract<
481 Extract<ToolCall, { readonly type: "ls" }>["result"],
482 { readonly status: "success" }
483 >["value"]["directoryTreeRoot"];
484
485 function cursorLsSearchResults(
486 node: CursorLsDirectoryNode,
487 path: Path.Path,
488 ): ReadonlyArray<{ readonly fileName: string }> {
489 return [
490 ...node.childrenFiles.map((file) => ({ fileName: path.join(node.absPath, file.name) })),
491 ...node.childrenDirs.flatMap((child) => cursorLsSearchResults(child, path)),
492 ];
493 }
494
495 function cursorToolSearchResults(
496 toolCall: ToolCall,
497 path: Path.Path,
498 ): ReadonlyArray<{
499 readonly fileName: string;
500 readonly line?: number;
501 readonly column?: number;
502 readonly preview?: string;
503 }> {
504 if (toolCall.result?.status !== "success") {
505 return [];
506 }
507 switch (toolCall.type) {
508 case "glob":
509 return toolCall.result.value.files.map((fileName) => ({ fileName }));
510 case "grep":
511 return Object.values(toolCall.result.value.workspaceResults ?? {}).flatMap((result) => {
512 if (result.type === "files") {
513 return result.output.files.map((fileName) => ({ fileName }));
514 }
515 if (result.type === "count") {
516 return result.output.counts.map((entry) => ({
517 fileName: entry.file,
518 preview: `${entry.count} ${entry.count === 1 ? "match" : "matches"}`,
519 }));
520 }
521 return result.output.matches.map((entry) => ({
522 fileName: entry.file,
523 ...(entry.lineNumber === undefined ? {} : { line: entry.lineNumber }),
524 preview: entry.line,
525 }));
526 });
527 case "ls":
528 return cursorLsSearchResults(toolCall.result.value.directoryTreeRoot, path);
529 case "readLints":
530 return toolCall.result.value.fileDiagnostics.flatMap((file) =>
531 file.diagnostics.map((diagnostic) => {
532 const line = diagnostic.range?.start?.line;
533 const character = diagnostic.range?.start?.character;
534 const hasLine = typeof line === "number" && Number.isInteger(line) && line >= 0;
535 return {
536 fileName: file.path,
537 ...(hasLine ? { line: line + 1 } : {}),
538 ...(hasLine &&
539 typeof character === "number" &&
540 Number.isInteger(character) &&
541 character >= 0
542 ? { column: character + 1 }
543 : {}),
544 preview: diagnostic.message,
545 };
546 }),
547 );
548 case "semSearch":
549 return [
550 {
551 fileName: "semantic-search",
552 preview: toolCall.result.value.results,
553 },
554 ];
555 default:
556 return [];
557 }
558 }
559
560 function cursorTodoSteps(
561 toolCall: Extract<ToolCall, { readonly type: "updateTodos" }>,
562 ): ReadonlyArray<OrchestrationV2PlanStep> {
563 const todos =
564 toolCall.result?.status === "success" ? toolCall.result.value.todos : toolCall.args.todos;
565 return todos
566 .filter((todo) => todo.status !== "cancelled" && todo.content.trim().length > 0)
567 .map((todo, index) => ({
568 id: `todo-${index + 1}`,
569 text: todo.content,
570 status:
571 todo.status === "inProgress"
572 ? "running"
573 : todo.status === "completed"
574 ? "completed"
575 : "pending",
576 }));
577 }
578
579 function assistantTextsFromConversationSteps(steps: ReadonlyArray<unknown>): ReadonlyArray<string> {
580 return steps.flatMap((step) => {
581 const record = unknownRecord(step);
582 if (record?.type === "assistantMessage") {
583 const text = nestedString(record, ["message", "text"]);
584 return text === undefined || text.length === 0 ? [] : [text];
585 }
586 const text = nestedString(record, ["assistantMessage", "text"]);
587 return text === undefined || text.length === 0 ? [] : [text];
588 });
589 }
590
591 function nestedToolResult<Value = Record<string, unknown>>(
592 rawResult: unknown,
593 mapSuccess: (success: Record<string, unknown>) => Value = (success) => success as Value,
594 ):
595 | { readonly status: "success"; readonly value: Value }
596 | { readonly status: "error"; readonly error: unknown }
597 | undefined {
598 const result = unknownRecord(rawResult);
599 if (result === undefined) {
600 return undefined;
601 }
602 const success = unknownRecord(result.success);
603 if (success !== undefined) {
604 return {
605 status: "success",
606 value: mapSuccess(success),
607 };
608 }
609 return {
610 status: "error",
611 error: result.error ?? result.permissionDenied ?? result,
612 };
613 }
614
615 function nestedGrepWorkspaceResults(success: Record<string, unknown>): Record<string, unknown> {
616 const workspaces = unknownRecord(success.workspaceResults);
617 if (workspaces === undefined) {
618 return {};
619 }
620 return Object.fromEntries(
621 Object.entries(workspaces).map(([workspace, rawWorkspaceResult]) => {
622 const workspaceResult = unknownRecord(rawWorkspaceResult);
623 const content = unknownRecord(workspaceResult?.content);
624 const rawMatches = Array.isArray(content?.matches) ? content.matches : [];
625 const matches = rawMatches.flatMap((rawFileMatch) => {
626 const fileMatch = unknownRecord(rawFileMatch);
627 const file = typeof fileMatch?.file === "string" ? fileMatch.file : "";
628 const lineMatches = Array.isArray(fileMatch?.matches) ? fileMatch.matches : [];
629 return lineMatches.flatMap((rawLineMatch) => {
630 const lineMatch = unknownRecord(rawLineMatch);
631 if (lineMatch === undefined) {
632 return [];
633 }
634 const line = typeof lineMatch.content === "string" ? lineMatch.content : undefined;
635 if (file.length === 0 || line === undefined) {
636 return [];
637 }
638 return [
639 {
640 file,
641 line,
642 ...(typeof lineMatch.lineNumber === "number"
643 ? { lineNumber: lineMatch.lineNumber }
644 : {}),
645 },
646 ];
647 });
648 });
649 return [
650 workspace,
651 {
652 type: "content",
653 output: {
654 matches,
655 totalMatches:
656 typeof content?.totalMatchedLines === "number"
657 ? content.totalMatchedLines
658 : matches.length,
659 },
660 },
661 ];
662 }),
663 );
664 }
665
666 function nestedArray(value: unknown): ReadonlyArray<unknown> {
667 return Array.isArray(value) ? value : [];
668 }
669
670 function nestedLsDirectory(rawNode: unknown): CursorLsDirectoryNode {
671 const node = unknownRecord(rawNode);
672 return {
673 absPath: typeof node?.absPath === "string" ? node.absPath : "",
674 childrenDirs: nestedArray(node?.childrenDirs).map(nestedLsDirectory),
675 childrenFiles: nestedArray(node?.childrenFiles).flatMap((rawFile) => {
676 const name = unknownRecord(rawFile)?.name;
677 return typeof name === "string" ? [{ name }] : [];
678 }),
679 childrenWereProcessed: node?.childrenWereProcessed === true,
680 fullSubtreeExtensionCounts: Object.fromEntries(
681 Object.entries(unknownRecord(node?.fullSubtreeExtensionCounts) ?? {}).filter(
682 (entry): entry is [string, number] => typeof entry[1] === "number",
683 ),
684 ),
685 numFiles: typeof node?.numFiles === "number" ? node.numFiles : 0,
686 };
687 }
688
689 export function nestedToolCallFromEnvelope(
690 envelope: Record<string, unknown>,
691 ): { readonly callId: string; readonly toolCall: ToolCall } | undefined {
692 const callId = typeof envelope.toolCallId === "string" ? envelope.toolCallId : undefined;
693 const wrapperEntry = Object.entries(envelope).find(([key]) => key.endsWith("ToolCall"));
694 if (wrapperEntry === undefined) {
695 return undefined;
696 }
697 const [wrapperName, rawCall] = wrapperEntry;
698 const call = unknownRecord(rawCall);
699 if (call === undefined) {
700 return undefined;
701 }
702 const args = unknownRecord(call.args) ?? {};
703 const fallbackCallId = `nested-${wrapperName}`;
704 const nestedCallId = callId ?? fallbackCallId;
705
706 switch (wrapperName) {
707 case "readToolCall": {
708 const success = unknownRecord(unknownRecord(call.result)?.success);
709 const path =
710 typeof args.path === "string"
711 ? args.path
712 : typeof success?.path === "string"
713 ? success.path
714 : "<unknown path>";
715 return {
716 callId: nestedCallId,
717 toolCall: {
718 type: "read",
719 args: { path },
720 result: nestedToolResult(call.result, (value) => ({
721 content: typeof value.content === "string" ? value.content : "",
722 totalLines: typeof value.totalLines === "number" ? value.totalLines : 0,
723 fileSize: typeof value.fileSize === "number" ? value.fileSize : 0,
724 })),
725 } as unknown as ToolCall,
726 };
727 }
728 case "globToolCall":
729 return {
730 callId: nestedCallId,
731 toolCall: {
732 type: "glob",
733 args: {
734 globPattern: typeof args.globPattern === "string" ? args.globPattern : "**/*",
735 ...(typeof args.targetDirectory === "string"
736 ? { targetDirectory: args.targetDirectory }
737 : {}),
738 },
739 result: nestedToolResult(call.result, (value) => ({
740 files: Array.isArray(value.files)
741 ? value.files.filter((file): file is string => typeof file === "string")
742 : [],
743 totalFiles: typeof value.totalFiles === "number" ? value.totalFiles : 0,
744 clientTruncated: false,
745 ripgrepTruncated: false,
746 })),
747 } as unknown as ToolCall,
748 };
749 case "grepToolCall":
750 return {
751 callId: nestedCallId,
752 toolCall: {
753 type: "grep",
754 args: {
755 pattern: typeof args.pattern === "string" ? args.pattern : "",
756 ...(typeof args.path === "string" ? { path: args.path } : {}),
757 ...(typeof args.glob === "string" ? { glob: args.glob } : {}),
758 ...(typeof args.outputMode === "string" ? { outputMode: args.outputMode } : {}),
759 ...(typeof args.caseInsensitive === "boolean"
760 ? { caseInsensitive: args.caseInsensitive }
761 : {}),
762 ...(typeof args.offset === "number" ? { offset: args.offset } : {}),
763 ...(typeof args.multiline === "boolean" ? { multiline: args.multiline } : {}),
764 },
765 result: nestedToolResult(call.result, (value) => ({
766 workspaceResults: nestedGrepWorkspaceResults(value),
767 })),
768 } as unknown as ToolCall,
769 };
770 case "shellToolCall": {
771 const rawResult = unknownRecord(call.result);
772 const permissionDenied = unknownRecord(rawResult?.permissionDenied);
773 const command =
774 typeof args.command === "string"
775 ? args.command
776 : typeof permissionDenied?.command === "string"
777 ? permissionDenied.command
778 : "<unknown command>";
779 return {
780 callId: nestedCallId,
781 toolCall: {
782 type: "shell",
783 args: { command },
784 result: nestedToolResult(call.result, (value) => ({
785 stdout: typeof value.stdout === "string" ? value.stdout : "",
786 stderr: typeof value.stderr === "string" ? value.stderr : "",
787 exitCode: typeof value.exitCode === "number" ? value.exitCode : 0,
788 signal: typeof value.signal === "string" ? value.signal : "",
789 executionTime: typeof value.executionTime === "number" ? value.executionTime : 0,
790 })),
791 } as unknown as ToolCall,
792 };
793 }
794 case "lsToolCall":
795 return {
796 callId: nestedCallId,
797 toolCall: {
798 type: "ls",
799 args: { path: typeof args.path === "string" ? args.path : "" },
800 result: nestedToolResult(call.result, (value) => ({
801 directoryTreeRoot: nestedLsDirectory(value.directoryTreeRoot),
802 })),
803 } as unknown as ToolCall,
804 };
805 case "readLintsToolCall":
806 return {
807 callId: nestedCallId,
808 toolCall: {
809 type: "readLints",
810 args: {
811 paths: nestedArray(args.paths).filter(
812 (path): path is string => typeof path === "string",
813 ),
814 },
815 result: nestedToolResult(call.result, (value) => ({
816 fileDiagnostics: nestedArray(value.fileDiagnostics).map((rawFile) => {
817 const file = unknownRecord(rawFile);
818 return {
819 path: typeof file?.path === "string" ? file.path : "",
820 diagnostics: nestedArray(file?.diagnostics).flatMap((rawDiagnostic) => {
821 const diagnostic = unknownRecord(rawDiagnostic);
822 return diagnostic === undefined
823 ? []
824 : [
825 {
826 ...diagnostic,
827 message: typeof diagnostic.message === "string" ? diagnostic.message : "",
828 },
829 ];
830 }),
831 };
832 }),
833 totalFiles: typeof value.totalFiles === "number" ? value.totalFiles : 0,
834 totalDiagnostics:
835 typeof value.totalDiagnostics === "number" ? value.totalDiagnostics : 0,
836 })),
837 } as unknown as ToolCall,
838 };
839 case "mcpToolCall":
840 return {
841 callId: nestedCallId,
842 toolCall: {
843 type: "mcp",
844 args,
845 result: nestedToolResult(call.result, (value) => ({
846 content: nestedArray(value.content).flatMap((rawPart) => {
847 const part = unknownRecord(rawPart);
848 return part === undefined ? [] : [part];
849 }),
850 isError: value.isError === true,
851 })),
852 } as unknown as ToolCall,
853 };
854 default: {
855 const type = wrapperName.slice(0, -"ToolCall".length);
856 return {
857 callId: nestedCallId,
858 toolCall: {
859 type,
860 args,
861 result: nestedToolResult(call.result),
862 } as unknown as ToolCall,
863 };
864 }
865 }
866 }
867
868 function toolCallsFromConversationSteps(
869 steps: ReadonlyArray<unknown>,
870 ): ReadonlyArray<{ readonly callId: string; readonly toolCall: ToolCall }> {
871 return steps.flatMap((step) => {
872 const record = unknownRecord(step);
873 if (record?.type === "toolCall") {
874 const message = unknownRecord(record.message);
875 return typeof message?.type === "string"
876 ? [
877 {
878 callId: typeof record.callId === "string" ? record.callId : `nested-${message.type}`,
879 toolCall: message as ToolCall,
880 },
881 ]
882 : [];
883 }
884 const envelope = unknownRecord(record?.toolCall);
885 const nested = envelope === undefined ? undefined : nestedToolCallFromEnvelope(envelope);
886 return nested === undefined ? [] : [nested];
887 });
888 }
889
890 function textFromAgentMessage(message: AgentMessage): string {
891 const value = message.message;
892 if (typeof value === "string") {
893 return value;
894 }
895 const direct =
896 nestedString(value, ["text"]) ??
897 nestedString(value, ["message", "text"]) ??
898 nestedString(value, ["userMessage", "text"]) ??
899 nestedString(value, ["assistantMessage", "text"]);
900 if (direct !== undefined) {
901 return direct;
902 }
903 const content = unknownRecord(value)?.content;
904 if (!Array.isArray(content)) {
905 return "";
906 }
907 return content
908 .flatMap((part) => {
909 const text = unknownRecord(part)?.text;
910 return typeof text === "string" ? [text] : [];
911 })
912 .join("");
913 }
914
915 interface CursorProjectionTarget {
916 readonly threadId: ThreadId;
917 readonly runId: ProviderAdapter.ProviderAdapterV2TurnInput["runId"] | null;
918 readonly rootNodeId: OrchestrationV2ExecutionNode["rootNodeId"];
919 readonly parentNodeId: OrchestrationV2ExecutionNode["id"];
920 readonly providerThreadId: OrchestrationV2ProviderThread["id"] | null;
921 readonly providerTurnId: OrchestrationV2ProviderTurn["id"] | null;
922 }
923
924 // Cursor results can omit output; retain more streamed fallback than the persisted tail.
925 const MAX_CURSOR_STREAMED_OUTPUT_CHARS = 256 * 1024;
926 // After a turn ends, a retryable stream error can make Cursor's SDK resume from
927 // an older checkpoint inside the same run. When those resumes save nothing, it
928 // ends the run with this error even though the answer was already delivered.
929 const CURSOR_RESUME_NO_PROGRESS_MESSAGE =
930 "Agent turn stopped after repeated resume attempts made no progress";
931
932 interface ActiveCursorToolCall {
933 readonly callId: string;
934 toolCall: ToolCall;
935 readonly target: CursorProjectionTarget;
936 readonly ordinal: number;
937 readonly startedAt: DateTime.Utc;
938 streamedOutput: string;
939 }
940
941 interface ActiveCursorSubagent {
942 task: OrchestrationV2Subagent;
943 toolCall: Extract<ToolCall, { readonly type: "task" }>;
944 readonly callId: string;
945 readonly childThreadId: ThreadId;
946 readonly childRootNodeId: OrchestrationV2ExecutionNode["id"];
947 readonly turnItemId: OrchestrationV2TurnItem["id"];
948 readonly turnItemOrdinal: number;
949 nextChildOrdinal: number;
950 resultProjected: boolean;
951 // Nested tools and text Cursor streamed live; the completion transcript fills in only the rest.
952 readonly liveToolCallIds: Set<string>;
953 streamedAssistantText: string;
954 readonly tools: Map<string, ActiveCursorToolCall>;
955 readonly assistant: ActiveCursorTextStream;
956 readonly reasoning: ActiveCursorTextStream;
957 }
958
959 interface ActiveCursorTextSegment {
960 readonly nativeItemId: string;
961 readonly startedAt: DateTime.Utc;
962 readonly ordinal: number;
963 text: string;
964 }
965
966 interface ActiveCursorTextStream {
967 current: ActiveCursorTextSegment | null;
968 nextSegment: number;
969 }
970
971 interface ActiveCursorTurn {
972 readonly input: ProviderAdapter.ProviderAdapterV2TurnInput;
973 readonly run: CursorAgentSdk.CursorAgentSdkRun;
974 readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
975 readonly startedAt: DateTime.Utc;
976 readonly completed: Deferred.Deferred<void, never>;
977 readonly itemOrdinals: Map<string, number>;
978 readonly tools: Map<string, ActiveCursorToolCall>;
979 readonly subagents: Map<string, ActiveCursorSubagent>;
980 readonly assistant: ActiveCursorTextStream;
981 assistantReply: CursorTransportFailure;
982 readonly reasoning: ActiveCursorTextStream;
983 /** The user text this run sent, before runtime instructions; absent for /compress and resume. */
984 readonly prompt: string | undefined;
985 readonly message: string | SDKUserMessage;
986 readonly runtimeInstructions: string | undefined;
987 compacted: boolean;
988 interrupted: boolean;
989 finalized: boolean;
990 /** The agent's latest turn ended and no new work has started since. */
991 turnEnded: boolean;
992 readonly session: CursorAgentSdk.CursorAgentSdkSession;
993 /** What Cursor billed for this run, summed over its turn-ended updates. */
994 usage: CursorTurnUsage | undefined;
995 }
996
997 type CursorTurnUsage = NonNullable<Extract<InteractionUpdate, { type: "turn-ended" }>["usage"]>;
998
999 const CURSOR_BACKGROUND_WAIT_INSTRUCTIONS =
1000 "To wait for a background shell you started (tests, a build), call `t3_background_wait` with its shell ID or pid before you end your turn. It returns at once, and T3 wakes you when the shell exits. Do not mark work you leave running, or PRs.";
1001
1002 const BACKGROUND_SHELL_DETAIL_COMMAND_MAX_LENGTH = 200;
1003
1004 function cursorBackgroundShellDetail(exit: {
1005 readonly command: string;
1006 readonly exitCode: number | undefined;
1007 readonly outputPath: string | undefined;
1008 }): string {
1009 const codePoints = [...exit.command];
1010 const command =
1011 codePoints.length > BACKGROUND_SHELL_DETAIL_COMMAND_MAX_LENGTH
1012 ? `${codePoints.slice(0, BACKGROUND_SHELL_DETAIL_COMMAND_MAX_LENGTH).join("")}...`
1013 : exit.command;
1014 const exitCode = exit.exitCode === undefined ? "" : ` (exit ${exit.exitCode})`;
1015 const header = `Background command completed${exitCode}: ${command}`;
1016 return exit.outputPath === undefined ? header : `${header}\n\nOutput: ${exit.outputPath}`;
1017 }
1018
1019 const addCursorTurnUsage = (
1020 total: CursorTurnUsage | undefined,
1021 usage: CursorTurnUsage,
1022 ): CursorTurnUsage => {
1023 if (total === undefined) return usage;
1024 const reasoningTokens =
1025 total.reasoningTokens === undefined && usage.reasoningTokens === undefined
1026 ? undefined
1027 : (total.reasoningTokens ?? 0) + (usage.reasoningTokens ?? 0);
1028 return {
1029 inputTokens: total.inputTokens + usage.inputTokens,
1030 outputTokens: total.outputTokens + usage.outputTokens,
1031 cacheReadTokens: total.cacheReadTokens + usage.cacheReadTokens,
1032 cacheWriteTokens: total.cacheWriteTokens + usage.cacheWriteTokens,
1033 ...(reasoningTokens === undefined ? {} : { reasoningTokens }),
1034 };
1035 };
1036
1037 interface CursorLiveAgent {
1038 readonly nativeThreadId: string;
1039 readonly storeCwd: string;
1040 readonly session: CursorAgentSdk.CursorAgentSdkSession;
1041 }
1042
1043 export interface CursorAdapterV2Options {
1044 readonly instanceId: ProviderInstanceId;
1045 readonly environment: NodeJS.ProcessEnv;
1046 readonly getModels?: () => ReadonlyArray<ServerProviderModel>;
1047 readonly getSdkModels?: () => ReadonlyArray<SDKModel>;
1048 }
1049
1050 export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
1051 options: CursorAdapterV2Options,
1052 ) {
1053 const fileSystem = yield* FileSystem.FileSystem;
1054 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1055 const path = yield* Path.Path;
1056 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1057 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
1058 const platform = yield* HostProcess.Platform;
1059 const host = yield* ProviderHost.ProviderHost;
1060 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
1061 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
1062 const adapterOptions = options;
1063 const apiKey = adapterOptions.environment.CURSOR_API_KEY?.trim() || undefined;
1064
1065 return ProviderAdapter.ProviderAdapterV2.of({
1066 instanceId: adapterOptions.instanceId,
1067 driver: CursorAgentSdk.CURSOR_PROVIDER,
1068 getCapabilities: Effect.fn("CursorAdapter.getCapabilities")(function () {
1069 return Effect.succeed(CursorProviderCapabilitiesV2);
1070 }),
1071 planSelectionTransition: Effect.fn("CursorAdapter.planSelectionTransition")(function () {
1072 return Effect.succeed(turnScopedSelectionTransition());
1073 }),
1074 openSession: Effect.fn("CursorAdapterV2.openSession")(
1075 function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {
1076 const sessionScope = yield* Effect.scope;
1077 const createdAt = yield* DateTime.now;
1078 const session = providerSession({
1079 providerSessionId: input.providerSessionId,
1080 providerInstanceId: adapterOptions.instanceId,
1081 cwd: input.runtimePolicy.cwd,
1082 model: input.modelSelection.model,
1083 now: createdAt,
1084 });
1085 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
1086 const liveAgent = yield* Ref.make<CursorLiveAgent | null>(null);
1087 // What the native conversation was told since it started or was last compacted.
1088 const told = yield* Ref.make<{
1089 readonly agent: string;
1090 readonly orchestration: boolean;
1091 readonly device: boolean;
1092 readonly backgroundWait: boolean;
1093 readonly runtime: string | undefined;
1094 } | null>(null);
1095 // Cursor drops a run cancelled before its first checkpoint, so the next message carries its prompt.
1096 const interruptedPrompt = yield* Ref.make<{
1097 readonly agent: string;
1098 readonly runId: string;
1099 readonly text: string;
1100 readonly message: string | SDKUserMessage;
1101 readonly runtimeInstructions: string | undefined;
1102 } | null>(null);
1103 // A native resume's own run may stop before it checkpoints; the request is still in history.
1104 const resumedAgent = yield* Ref.make<string | null>(null);
1105 const warnedUnsupportedSandbox = yield* Ref.make(false);
1106 const activeTurn = yield* Ref.make<ActiveCursorTurn | null>(null);
1107 // Background shells the agent left running, by the shell id Cursor gave it.
1108 const backgroundShells = new Map<
1109 string,
1110 {
1111 readonly providerThreadId: OrchestrationV2ProviderThread["id"];
1112 readonly runId: ProviderAdapter.ProviderAdapterV2TurnInput["runId"];
1113 readonly pid: number | undefined;
1114 readonly command: string;
1115 readonly stop: () => void;
1116 awaited: boolean;
1117 }
1118 >();
1119 // Runs a Stop ended; a shell they started that is reported only afterwards is stopped too.
1120 const stoppedRuns = new Set<ProviderAdapter.ProviderAdapterV2TurnInput["runId"]>();
1121 let latestRunId: ProviderAdapter.ProviderAdapterV2TurnInput["runId"] | undefined;
1122 // A Stop or rollback bumps this, which drops wakes still queued behind another run.
1123 let wakeGeneration = 0;
1124 const publishedProviderThread = yield* Ref.make<OrchestrationV2ProviderThread | null>(null);
1125 const planIds = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact["id"]>());
1126
1127 const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) =>
1128 Queue.offer(events, event).pipe(Effect.asVoid);
1129
1130 const withBackgroundShells = (
1131 providerThread: OrchestrationV2ProviderThread,
1132 ): OrchestrationV2ProviderThread => ({
1133 ...providerThread,
1134 pendingBackgroundTasks: [...backgroundShells].flatMap(([taskId, shell]) =>
1135 shell.providerThreadId === providerThread.id
1136 ? [
1137 {
1138 taskId,
1139 kind: "command" as const,
1140 command: shell.command,
1141 ...(shell.command.trim().length === 0
1142 ? {}
1143 : { description: shell.command.trim() }),
1144 ...(shell.awaited ? { awaited: true as const } : {}),
1145 },
1146 ]
1147 : [],
1148 ),
1149 });
1150
1151 const emitProviderThread = Effect.fn("CursorAdapterV2.emitProviderThread")(function* (
1152 providerThread: OrchestrationV2ProviderThread,
1153 sessionScoped = false,
1154 ) {
1155 const listed = withBackgroundShells(providerThread);
1156 yield* Ref.set(publishedProviderThread, listed);
1157 yield* emitProviderEvent({
1158 type: "provider_thread.updated",
1159 driver: CursorAgentSdk.CURSOR_PROVIDER,
1160 providerThread: listed,
1161 ...(sessionScoped ? { sessionScoped: true } : {}),
1162 });
1163 });
1164
1165 const publishBackgroundShells = Effect.fn("CursorAdapterV2.publishBackgroundShells")(
1166 function* (providerThreadId: OrchestrationV2ProviderThread["id"]) {
1167 const published = yield* Ref.get(publishedProviderThread);
1168 if (published?.id !== providerThreadId) return;
1169 const turn = yield* Ref.get(activeTurn);
1170 // No run reads this stream between turns, so the session stores the snapshot itself.
1171 yield* emitProviderThread(
1172 { ...published, updatedAt: yield* DateTime.now },
1173 turn === null || turn.finalized,
1174 );
1175 },
1176 );
1177
1178 const onBackgroundShell = Effect.fn("CursorAdapterV2.onBackgroundShell")(function* (
1179 turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
1180 shell: CursorAgentSdk.CursorBackgroundShellEvent,
1181 ) {
1182 const providerThreadId = turnInput.providerThread.id;
1183 if (shell.type === "started") {
1184 if (stoppedRuns.has(turnInput.runId)) return shell.stop();
1185 backgroundShells.set(shell.id, {
1186 providerThreadId,
1187 runId: turnInput.runId,
1188 pid: shell.pid,
1189 command: shell.command,
1190 stop: shell.stop,
1191 awaited: false,
1192 });
1193 return yield* publishBackgroundShells(providerThreadId);
1194 }
1195 const started = backgroundShells.get(shell.id);
1196 if (started === undefined) return;
1197 backgroundShells.delete(shell.id);
1198 yield* publishBackgroundShells(providerThreadId);
1199 // Nobody waits to hear about a shell the agent or a Stop killed.
1200 if (shell.stopped) return;
1201 // The run that started it is still working, so the agent can read the result itself.
1202 const turn = yield* Ref.get(activeTurn);
1203 if (
1204 turn !== null &&
1205 !turn.finalized &&
1206 !turn.turnEnded &&
1207 turn.input.runId === started.runId
1208 ) {
1209 return;
1210 }
1211 const generation = wakeGeneration;
1212 yield* continuationRequests.offer({
1213 threadId: turnInput.threadId,
1214 providerThreadId,
1215 driver: CursorAgentSdk.CURSOR_PROVIDER,
1216 dispatchIfCurrent: (dispatch) =>
1217 generation === wakeGeneration ? Effect.asSome(dispatch) : Effect.succeedNone,
1218 // Cursor starts a new run from this text, so nothing is buffered.
1219 delivery: "message_text",
1220 detail: cursorBackgroundShellDetail(shell),
1221 notification: {
1222 ...backgroundWorkNotification([
1223 {
1224 kind: "command",
1225 label: shell.command,
1226 outcome:
1227 shell.exitCode === 0
1228 ? "completed"
1229 : shell.exitCode === undefined
1230 ? "unknown"
1231 : "failed",
1232 exitCode: shell.exitCode,
1233 },
1234 ]),
1235 detail: shell.command,
1236 },
1237 });
1238 });
1239
1240 const stopBackgroundShells = (providerThreadId?: OrchestrationV2ProviderThread["id"]) =>
1241 Effect.sync(() => {
1242 wakeGeneration += 1;
1243 for (const shell of backgroundShells.values()) {
1244 if (providerThreadId === undefined || shell.providerThreadId === providerThreadId) {
1245 shell.stop();
1246 }
1247 }
1248 });
1249
1250 const resolveItemOrdinal = (context: ActiveCursorTurn, nativeItemId: string) =>
1251 Effect.sync(() => {
1252 const existing = context.itemOrdinals.get(nativeItemId);
1253 if (existing !== undefined) {
1254 return existing;
1255 }
1256 const ordinal = context.input.providerTurnOrdinal * 100 + context.itemOrdinals.size + 1;
1257 context.itemOrdinals.set(nativeItemId, ordinal);
1258 return ordinal;
1259 });
1260
1261 const resolvePlanId = Effect.fnUntraced(function* (
1262 context: ActiveCursorTurn,
1263 nativeItemId: string,
1264 ) {
1265 const existing = (yield* Ref.get(planIds)).get(nativeItemId);
1266 if (existing !== undefined) {
1267 return existing;
1268 }
1269 const planId = yield* idAllocator.allocate.plan({
1270 threadId: context.input.threadId,
1271 runId: context.input.runId,
1272 driver: CursorAgentSdk.CURSOR_PROVIDER,
1273 });
1274 yield* Ref.update(planIds, (current) => {
1275 const updated = new Map(current);
1276 updated.set(nativeItemId, planId);
1277 return updated;
1278 });
1279 return planId;
1280 });
1281
1282 const parentTarget = (context: ActiveCursorTurn): CursorProjectionTarget => ({
1283 threadId: context.input.threadId,
1284 runId: context.input.runId,
1285 rootNodeId: context.input.rootNodeId,
1286 parentNodeId: context.input.rootNodeId,
1287 providerThreadId: context.input.providerThread.id,
1288 providerTurnId: context.providerTurnId,
1289 });
1290
1291 const childProjectionTarget = (subagent: ActiveCursorSubagent): CursorProjectionTarget => ({
1292 threadId: subagent.childThreadId,
1293 runId: null,
1294 rootNodeId: subagent.childRootNodeId,
1295 parentNodeId: subagent.childRootNodeId,
1296 providerThreadId: null,
1297 providerTurnId: null,
1298 });
1299
1300 const emitAssistant = Effect.fnUntraced(function* (
1301 target: CursorProjectionTarget,
1302 segment: ActiveCursorTextSegment | null,
1303 completed: boolean,
1304 ) {
1305 if (segment === null || segment.text.length === 0) {
1306 return;
1307 }
1308 const now = yield* DateTime.now;
1309 const nodeId = idAllocator.derive.nodeFromProviderItem({
1310 driver: CursorAgentSdk.CURSOR_PROVIDER,
1311 nativeItemId: segment.nativeItemId,
1312 });
1313 const messageId = idAllocator.derive.messageFromProviderItem({
1314 driver: CursorAgentSdk.CURSOR_PROVIDER,
1315 nativeItemId: segment.nativeItemId,
1316 });
1317 const turnItemId = idAllocator.derive.turnItemFromProviderItem({
1318 driver: CursorAgentSdk.CURSOR_PROVIDER,
1319 nativeItemId: segment.nativeItemId,
1320 });
1321 const nativeItemRef = {
1322 driver: CursorAgentSdk.CURSOR_PROVIDER,
1323 nativeId: segment.nativeItemId,
1324 strength: "weak" as const,
1325 };
1326 yield* emitProviderEvent({
1327 type: "node.updated",
1328 driver: CursorAgentSdk.CURSOR_PROVIDER,
1329 node: {
1330 id: nodeId,
1331 threadId: target.threadId,
1332 runId: target.runId,
1333 parentNodeId: target.parentNodeId,
1334 rootNodeId: target.rootNodeId,
1335 kind: "assistant_message",
1336 status: completed ? "completed" : "running",
1337 countsForRun: false,
1338 providerThreadId: target.providerThreadId,
1339 providerTurnId: target.providerTurnId,
1340 nativeItemRef,
1341 runtimeRequestId: null,
1342 checkpointScopeId: null,
1343 startedAt: segment.startedAt,
1344 completedAt: completed ? now : null,
1345 },
1346 });
1347 yield* emitProviderEvent({
1348 type: "message.updated",
1349 driver: CursorAgentSdk.CURSOR_PROVIDER,
1350 message: {
1351 createdBy: "agent",
1352 creationSource: "provider",
1353 id: messageId,
1354 threadId: target.threadId,
1355 runId: target.runId,
1356 nodeId,
1357 role: "assistant",
1358 text: segment.text,
1359 attachments: [],
1360 streaming: !completed,
1361 createdAt: segment.startedAt,
1362 updatedAt: now,
1363 },
1364 });
1365 yield* emitProviderEvent({
1366 type: "turn_item.updated",
1367 driver: CursorAgentSdk.CURSOR_PROVIDER,
1368 turnItem: {
1369 id: turnItemId,
1370 threadId: target.threadId,
1371 runId: target.runId,
1372 nodeId,
1373 providerThreadId: target.providerThreadId,
1374 providerTurnId: target.providerTurnId,
1375 nativeItemRef,
1376 parentItemId: null,
1377 ordinal: segment.ordinal,
1378 status: completed ? "completed" : "running",
1379 title: null,
1380 startedAt: segment.startedAt,
1381 completedAt: completed ? now : null,
1382 updatedAt: now,
1383 type: "assistant_message",
1384 messageId,
1385 text: segment.text,
1386 streaming: !completed,
1387 },
1388 });
1389 });
1390
1391 const emitReasoning = Effect.fnUntraced(function* (
1392 target: CursorProjectionTarget,
1393 segment: ActiveCursorTextSegment | null,
1394 completed: boolean,
1395 ) {
1396 if (segment === null || segment.text.length === 0) {
1397 return;
1398 }
1399 const now = yield* DateTime.now;
1400 const nodeId = idAllocator.derive.nodeFromProviderItem({
1401 driver: CursorAgentSdk.CURSOR_PROVIDER,
1402 nativeItemId: segment.nativeItemId,
1403 });
1404 const turnItemId = idAllocator.derive.turnItemFromProviderItem({
1405 driver: CursorAgentSdk.CURSOR_PROVIDER,
1406 nativeItemId: segment.nativeItemId,
1407 });
1408 const nativeItemRef = {
1409 driver: CursorAgentSdk.CURSOR_PROVIDER,
1410 nativeId: segment.nativeItemId,
1411 strength: "weak" as const,
1412 };
1413 yield* emitProviderEvent({
1414 type: "node.updated",
1415 driver: CursorAgentSdk.CURSOR_PROVIDER,
1416 node: {
1417 id: nodeId,
1418 threadId: target.threadId,
1419 runId: target.runId,
1420 parentNodeId: target.parentNodeId,
1421 rootNodeId: target.rootNodeId,
1422 kind: "reasoning",
1423 status: completed ? "completed" : "running",
1424 countsForRun: false,
1425 providerThreadId: target.providerThreadId,
1426 providerTurnId: target.providerTurnId,
1427 nativeItemRef,
1428 runtimeRequestId: null,
1429 checkpointScopeId: null,
1430 startedAt: segment.startedAt,
1431 completedAt: completed ? now : null,
1432 },
1433 });
1434 yield* emitProviderEvent({
1435 type: "turn_item.updated",
1436 driver: CursorAgentSdk.CURSOR_PROVIDER,
1437 turnItem: {
1438 id: turnItemId,
1439 threadId: target.threadId,
1440 runId: target.runId,
1441 nodeId,
1442 providerThreadId: target.providerThreadId,
1443 providerTurnId: target.providerTurnId,
1444 nativeItemRef,
1445 parentItemId: null,
1446 ordinal: segment.ordinal,
1447 status: completed ? "completed" : "running",
1448 title: null,
1449 startedAt: segment.startedAt,
1450 completedAt: completed ? now : null,
1451 updatedAt: now,
1452 type: "reasoning",
1453 text: segment.text,
1454 streaming: !completed,
1455 },
1456 });
1457 });
1458
1459 const appendTextSegment = Effect.fnUntraced(function* (input: {
1460 readonly context: ActiveCursorTurn;
1461 readonly stream: ActiveCursorTextStream;
1462 readonly kind: "assistant" | "reasoning";
1463 readonly text: string;
1464 }) {
1465 if (input.stream.current === null) {
1466 input.stream.nextSegment += 1;
1467 const nativeItemId = `${input.kind}:${input.context.run.runId}:${input.stream.nextSegment}`;
1468 input.stream.current = {
1469 nativeItemId,
1470 startedAt: yield* DateTime.now,
1471 ordinal: yield* resolveItemOrdinal(input.context, nativeItemId),
1472 text: "",
1473 };
1474 }
1475 input.stream.current.text += input.text;
1476 });
1477
1478 const completeAssistant = Effect.fnUntraced(function* (context: ActiveCursorTurn) {
1479 if (context.assistant.current === null) {
1480 return;
1481 }
1482 yield* emitAssistant(parentTarget(context), context.assistant.current, true);
1483 context.assistant.current = null;
1484 });
1485
1486 const completeReasoning = Effect.fnUntraced(function* (context: ActiveCursorTurn) {
1487 if (context.reasoning.current === null) {
1488 return;
1489 }
1490 yield* emitReasoning(parentTarget(context), context.reasoning.current, true);
1491 context.reasoning.current = null;
1492 });
1493
1494 const emitToolArtifacts = Effect.fnUntraced(function* (input: {
1495 readonly active: ActiveCursorToolCall;
1496 readonly completed: boolean;
1497 readonly unfinishedStatus?: "interrupted" | "failed" | "cancelled";
1498 }) {
1499 const { active } = input;
1500 const toolCall = active.toolCall;
1501 const now = yield* DateTime.now;
1502 const failed = input.completed && cursorToolFailed(toolCall);
1503 const status = !input.completed
1504 ? "running"
1505 : (input.unfinishedStatus ?? (failed ? "failed" : "completed"));
1506 const nodeId = idAllocator.derive.nodeFromProviderItem({
1507 driver: CursorAgentSdk.CURSOR_PROVIDER,
1508 nativeItemId: active.callId,
1509 });
1510 const turnItemId = idAllocator.derive.turnItemFromProviderItem({
1511 driver: CursorAgentSdk.CURSOR_PROVIDER,
1512 nativeItemId: active.callId,
1513 });
1514 const nativeItemRef = {
1515 driver: CursorAgentSdk.CURSOR_PROVIDER,
1516 nativeId: active.callId,
1517 strength: "strong" as const,
1518 };
1519 const node: OrchestrationV2ExecutionNode = {
1520 id: nodeId,
1521 threadId: active.target.threadId,
1522 runId: active.target.runId,
1523 parentNodeId: active.target.parentNodeId,
1524 rootNodeId: active.target.rootNodeId,
1525 kind: "tool_call",
1526 status,
1527 countsForRun: false,
1528 providerThreadId: active.target.providerThreadId,
1529 providerTurnId: active.target.providerTurnId,
1530 nativeItemRef,
1531 runtimeRequestId: null,
1532 checkpointScopeId: null,
1533 startedAt: active.startedAt,
1534 completedAt: input.completed ? now : null,
1535 };
1536 const base = {
1537 id: turnItemId,
1538 threadId: active.target.threadId,
1539 runId: active.target.runId,
1540 nodeId,
1541 providerThreadId: active.target.providerThreadId,
1542 providerTurnId: active.target.providerTurnId,
1543 nativeItemRef,
1544 parentItemId: null,
1545 ordinal: active.ordinal,
1546 status,
1547 title: null,
1548 startedAt: active.startedAt,
1549 completedAt: input.completed ? now : null,
1550 updatedAt: now,
1551 } satisfies Pick<
1552 OrchestrationV2TurnItem,
1553 | "id"
1554 | "threadId"
1555 | "runId"
1556 | "nodeId"
1557 | "providerThreadId"
1558 | "providerTurnId"
1559 | "nativeItemRef"
1560 | "parentItemId"
1561 | "ordinal"
1562 | "status"
1563 | "title"
1564 | "startedAt"
1565 | "completedAt"
1566 | "updatedAt"
1567 >;
1568 const outputText =
1569 cursorToolOutputText(toolCall) ||
1570 active.streamedOutput.slice(-MAX_CURSOR_STREAMED_OUTPUT_CHARS);
1571 let turnItem: OrchestrationV2TurnItem;
1572 switch (toolCall.type) {
1573 case "shell":
1574 turnItem = {
1575 ...base,
1576 type: "command_execution",
1577 input: toolCall.args.command,
1578 ...(outputText.length === 0 ? {} : { output: outputText }),
1579 ...(toolCall.result?.status === "success"
1580 ? { exitCode: toolCall.result.value.exitCode }
1581 : {}),
1582 };
1583 break;
1584 case "write":
1585 case "delete":
1586 case "edit":
1587 case "generateImage":
1588 turnItem = {
1589 ...base,
1590 type: "file_change",
1591 fileName: cursorToolFileName(toolCall),
1592 ...(toolCall.type === "edit" &&
1593 toolCall.result?.status === "success" &&
1594 toolCall.result.value.linesAdded !== undefined
1595 ? { additions: toolCall.result.value.linesAdded }
1596 : {}),
1597 ...(toolCall.type === "edit" &&
1598 toolCall.result?.status === "success" &&
1599 toolCall.result.value.linesRemoved !== undefined
1600 ? { deletions: toolCall.result.value.linesRemoved }
1601 : {}),
1602 ...(toolCall.type === "edit" &&
1603 toolCall.result?.status === "success" &&
1604 toolCall.result.value.diffString !== undefined
1605 ? { diffStr: toolCall.result.value.diffString }
1606 : toolCall.result?.status === "error" && outputText.trim().length > 0
1607 ? { diffStr: outputText }
1608 : {}),
1609 ...(toolCall.type === "write" ? { newStr: toolCall.args.fileText } : {}),
1610 };
1611 break;
1612 case "read":
1613 turnItem = {
1614 ...base,
1615 title: formatReadToolLabel(toolCall.args.path),
1616 type: "dynamic_tool",
1617 toolName: "Read",
1618 input: toolCall.args,
1619 ...(cursorToolOutput(toolCall) === undefined
1620 ? {}
1621 : { output: cursorToolOutput(toolCall) }),
1622 };
1623 break;
1624 case "glob":
1625 case "grep":
1626 case "ls":
1627 case "readLints":
1628 case "semSearch": {
1629 const pattern = cursorToolSearchPattern(toolCall);
1630 const searchPath =
1631 toolCall.type === "grep"
1632 ? toolCall.args.path
1633 : toolCall.type === "glob"
1634 ? toolCall.args.targetDirectory
1635 : toolCall.type === "semSearch"
1636 ? toolCall.args.targetDirectories?.join(", ")
1637 : pattern;
1638 const results =
1639 toolCall.result?.status === "error" && outputText.trim().length > 0
1640 ? [{ fileName: searchPath?.trim() || ".", preview: outputText }]
1641 : cursorToolSearchResults(toolCall, path);
1642 turnItem = {
1643 ...base,
1644 title:
1645 formatSearchToolLabel({
1646 input: toolCall.args,
1647 ...(pattern === undefined ? {} : { pattern }),
1648 }) ?? null,
1649 type: "file_search",
1650 ...(pattern === undefined ? {} : { pattern }),
1651 ...(results.length === 0 ? {} : { results: [...results] }),
1652 };
1653 break;
1654 }
1655 default:
1656 turnItem = {
1657 ...base,
1658 type: "dynamic_tool",
1659 ...(toolCall.type === "mcp"
1660 ? mcpToolPresentation({
1661 serverName: toolCall.args.providerIdentifier,
1662 toolName: toolCall.args.toolName,
1663 })
1664 : {}),
1665 toolName: cursorToolName(toolCall),
1666 input: toolCall.type === "mcp" ? (toolCall.args.args ?? {}) : toolCall.args,
1667 ...(cursorToolOutput(toolCall) === undefined
1668 ? {}
1669 : { output: cursorToolOutput(toolCall) }),
1670 };
1671 }
1672 yield* emitProviderEvent({
1673 type: "node.updated",
1674 driver: CursorAgentSdk.CURSOR_PROVIDER,
1675 node,
1676 });
1677 yield* emitProviderEvent({
1678 type: "turn_item.updated",
1679 driver: CursorAgentSdk.CURSOR_PROVIDER,
1680 turnItem,
1681 });
1682 });
1683
1684 const ensureToolStarted = Effect.fnUntraced(function* (
1685 context: ActiveCursorTurn,
1686 callId: string,
1687 toolCall: ToolCall,
1688 ) {
1689 const existing = context.tools.get(callId);
1690 if (existing !== undefined) {
1691 existing.toolCall = toolCall;
1692 return existing;
1693 }
1694 const startedAt = yield* DateTime.now;
1695 const active: ActiveCursorToolCall = {
1696 callId,
1697 toolCall,
1698 target: parentTarget(context),
1699 ordinal: yield* resolveItemOrdinal(context, callId),
1700 startedAt,
1701 streamedOutput: "",
1702 };
1703 context.tools.set(callId, active);
1704 yield* emitToolArtifacts({ active, completed: false });
1705 return active;
1706 });
1707
1708 const emitPlanArtifacts = Effect.fnUntraced(function* (input: {
1709 readonly context: ActiveCursorTurn;
1710 readonly callId: string;
1711 readonly markdown: string;
1712 readonly completed: boolean;
1713 readonly failed: boolean;
1714 }) {
1715 const nativeItemId = `plan:${input.callId}`;
1716 const now = yield* DateTime.now;
1717 const planId = yield* resolvePlanId(input.context, nativeItemId);
1718 const ordinal = yield* resolveItemOrdinal(input.context, nativeItemId);
1719 const nodeId = idAllocator.derive.nodeFromProviderItem({
1720 driver: CursorAgentSdk.CURSOR_PROVIDER,
1721 nativeItemId,
1722 });
1723 const turnItemId = idAllocator.derive.turnItemFromProviderItem({
1724 driver: CursorAgentSdk.CURSOR_PROVIDER,
1725 nativeItemId,
1726 });
1727 const status = input.failed ? "failed" : input.completed ? "completed" : "running";
1728 const nativeItemRef = {
1729 driver: CursorAgentSdk.CURSOR_PROVIDER,
1730 nativeId: input.callId,
1731 strength: "strong" as const,
1732 };
1733 const plan: OrchestrationV2PlanArtifact = {
1734 id: planId,
1735 threadId: input.context.input.threadId,
1736 runId: input.context.input.runId,
1737 nodeId,
1738 kind: "proposed_plan",
1739 status: input.completed ? "active" : "draft",
1740 markdown: input.markdown,
1741 };
1742 yield* emitProviderEvent({
1743 type: "node.updated",
1744 driver: CursorAgentSdk.CURSOR_PROVIDER,
1745 node: {
1746 id: nodeId,
1747 threadId: input.context.input.threadId,
1748 runId: input.context.input.runId,
1749 parentNodeId: input.context.input.rootNodeId,
1750 rootNodeId: input.context.input.rootNodeId,
1751 kind: "plan",
1752 status,
1753 countsForRun: false,
1754 providerThreadId: input.context.input.providerThread.id,
1755 providerTurnId: input.context.providerTurnId,
1756 nativeItemRef,
1757 runtimeRequestId: null,
1758 checkpointScopeId: null,
1759 startedAt: input.context.startedAt,
1760 completedAt: input.completed ? now : null,
1761 },
1762 });
1763 yield* emitProviderEvent({
1764 type: "plan.updated",
1765 driver: CursorAgentSdk.CURSOR_PROVIDER,
1766 plan,
1767 });
1768 yield* emitProviderEvent({
1769 type: "turn_item.updated",
1770 driver: CursorAgentSdk.CURSOR_PROVIDER,
1771 turnItem: {
1772 id: turnItemId,
1773 threadId: input.context.input.threadId,
1774 runId: input.context.input.runId,
1775 nodeId,
1776 providerThreadId: input.context.input.providerThread.id,
1777 providerTurnId: input.context.providerTurnId,
1778 nativeItemRef,
1779 parentItemId: null,
1780 ordinal,
1781 status,
1782 title: null,
1783 startedAt: input.context.startedAt,
1784 completedAt: input.completed ? now : null,
1785 updatedAt: now,
1786 type: "proposed_plan",
1787 planId,
1788 markdown: input.markdown,
1789 streaming: !input.completed,
1790 },
1791 });
1792 });
1793
1794 const emitTodoArtifacts = Effect.fnUntraced(function* (input: {
1795 readonly context: ActiveCursorTurn;
1796 readonly callId: string;
1797 readonly toolCall: Extract<ToolCall, { readonly type: "updateTodos" }>;
1798 readonly completed: boolean;
1799 readonly failed: boolean;
1800 }) {
1801 const nativeItemId = `todos:${input.callId}`;
1802 const now = yield* DateTime.now;
1803 const planId = yield* resolvePlanId(input.context, nativeItemId);
1804 const ordinal = yield* resolveItemOrdinal(input.context, nativeItemId);
1805 const nodeId = idAllocator.derive.nodeFromProviderItem({
1806 driver: CursorAgentSdk.CURSOR_PROVIDER,
1807 nativeItemId,
1808 });
1809 const turnItemId = idAllocator.derive.turnItemFromProviderItem({
1810 driver: CursorAgentSdk.CURSOR_PROVIDER,
1811 nativeItemId,
1812 });
1813 const status = input.failed ? "failed" : input.completed ? "completed" : "running";
1814 const steps = cursorTodoSteps(input.toolCall);
1815 const nativeItemRef = {
1816 driver: CursorAgentSdk.CURSOR_PROVIDER,
1817 nativeId: input.callId,
1818 strength: "strong" as const,
1819 };
1820 yield* emitProviderEvent({
1821 type: "node.updated",
1822 driver: CursorAgentSdk.CURSOR_PROVIDER,
1823 node: {
1824 id: nodeId,
1825 threadId: input.context.input.threadId,
1826 runId: input.context.input.runId,
1827 parentNodeId: input.context.input.rootNodeId,
1828 rootNodeId: input.context.input.rootNodeId,
1829 kind: "todo_list",
1830 status,
1831 countsForRun: false,
1832 providerThreadId: input.context.input.providerThread.id,
1833 providerTurnId: input.context.providerTurnId,
1834 nativeItemRef,
1835 runtimeRequestId: null,
1836 checkpointScopeId: null,
1837 startedAt: input.context.startedAt,
1838 completedAt: input.completed ? now : null,
1839 },
1840 });
1841 yield* emitProviderEvent({
1842 type: "plan.updated",
1843 driver: CursorAgentSdk.CURSOR_PROVIDER,
1844 plan: {
1845 id: planId,
1846 threadId: input.context.input.threadId,
1847 runId: input.context.input.runId,
1848 nodeId,
1849 kind: "todo_list",
1850 status: input.completed ? "active" : "draft",
1851 steps: [...steps],
1852 },
1853 });
1854 yield* emitProviderEvent({
1855 type: "turn_item.updated",
1856 driver: CursorAgentSdk.CURSOR_PROVIDER,
1857 turnItem: {
1858 id: turnItemId,
1859 threadId: input.context.input.threadId,
1860 runId: input.context.input.runId,
1861 nodeId,
1862 providerThreadId: input.context.input.providerThread.id,
1863 providerTurnId: input.context.providerTurnId,
1864 nativeItemRef,
1865 parentItemId: null,
1866 ordinal,
1867 status,
1868 title: null,
1869 startedAt: input.context.startedAt,
1870 completedAt: input.completed ? now : null,
1871 updatedAt: now,
1872 type: "todo_list",
1873 planId,
1874 steps: [...steps],
1875 },
1876 });
1877 });
1878
1879 const emitSubagent = Effect.fnUntraced(function* (input: {
1880 readonly context: ActiveCursorTurn;
1881 readonly callId: string;
1882 readonly toolCall: Extract<ToolCall, { readonly type: "task" }>;
1883 readonly completed: boolean;
1884 readonly status?: OrchestrationV2Subagent["status"];
1885 }) {
1886 const args = input.toolCall.args;
1887 const result =
1888 input.toolCall.result?.status === "success" ? input.toolCall.result.value : undefined;
1889 const existing = input.context.subagents.get(input.callId);
1890 if (
1891 existing !== undefined &&
1892 !isOrchestrationV2WorkActive(existing.task.status) &&
1893 !input.completed
1894 )
1895 return;
1896 const now = yield* DateTime.now;
1897 const status: OrchestrationV2Subagent["status"] =
1898 input.status ??
1899 (input.completed
1900 ? cursorToolFailed(input.toolCall)
1901 ? "failed"
1902 : "completed"
1903 : "running");
1904 const resultParts = [
1905 ...assistantTextsFromConversationSteps(result?.conversationSteps ?? []),
1906 ...(result?.resultSuffix === undefined ? [] : [result.resultSuffix]),
1907 ].filter((part) => part.trim().length > 0);
1908 const resultText = resultParts.join("\n");
1909 const nativeItemId = input.callId;
1910 const nodeId =
1911 existing?.task.id ??
1912 idAllocator.derive.nodeFromProviderItem({
1913 driver: CursorAgentSdk.CURSOR_PROVIDER,
1914 nativeItemId,
1915 });
1916 const childRootNodeId =
1917 existing?.childRootNodeId ??
1918 idAllocator.derive.nodeFromProviderItem({
1919 driver: CursorAgentSdk.CURSOR_PROVIDER,
1920 nativeItemId: `${nativeItemId}:child-root`,
1921 });
1922 const childThreadId =
1923 existing?.childThreadId ??
1924 idAllocator.derive.subagentThread({
1925 driver: CursorAgentSdk.CURSOR_PROVIDER,
1926 nativeThreadId: `${input.context.run.runId}:task:${input.callId}`,
1927 });
1928 const task: OrchestrationV2Subagent = {
1929 ...(existing?.task ?? {
1930 id: nodeId,
1931 threadId: input.context.input.threadId,
1932 runId: input.context.input.runId,
1933 parentNodeId: input.context.input.rootNodeId,
1934 origin: "provider_native" as const,
1935 createdBy: "agent" as const,
1936 driver: CursorAgentSdk.CURSOR_PROVIDER,
1937 providerInstanceId: input.context.input.modelSelection.instanceId,
1938 providerThreadId: null,
1939 childThreadId,
1940 nativeTaskRef: {
1941 driver: CursorAgentSdk.CURSOR_PROVIDER,
1942 nativeId: input.callId,
1943 strength: "strong" as const,
1944 },
1945 prompt: args.prompt,
1946 title: args.description,
1947 result: null,
1948 startedAt: now,
1949 }),
1950 model: args.model?.trim() || existing?.task.model || null,
1951 nativeTaskRef: {
1952 driver: CursorAgentSdk.CURSOR_PROVIDER,
1953 nativeId: input.callId,
1954 strength: "strong" as const,
1955 },
1956 status,
1957 result: resultText.length === 0 ? (existing?.task.result ?? null) : resultText,
1958 completedAt: input.completed ? (existing?.task.completedAt ?? now) : null,
1959 updatedAt: now,
1960 };
1961 const subagent: ActiveCursorSubagent = {
1962 task,
1963 toolCall: input.toolCall,
1964 callId: input.callId,
1965 childThreadId,
1966 childRootNodeId,
1967 turnItemId:
1968 existing?.turnItemId ??
1969 idAllocator.derive.turnItemFromProviderItem({
1970 driver: CursorAgentSdk.CURSOR_PROVIDER,
1971 nativeItemId,
1972 }),
1973 turnItemOrdinal:
1974 existing?.turnItemOrdinal ?? (yield* resolveItemOrdinal(input.context, nativeItemId)),
1975 nextChildOrdinal: existing?.nextChildOrdinal ?? 100,
1976 resultProjected: existing?.resultProjected ?? false,
1977 liveToolCallIds: existing?.liveToolCallIds ?? new Set(),
1978 streamedAssistantText: existing?.streamedAssistantText ?? "",
1979 tools: existing?.tools ?? new Map(),
1980 assistant: existing?.assistant ?? { current: null, nextSegment: 0 },
1981 reasoning: existing?.reasoning ?? { current: null, nextSegment: 0 },
1982 };
1983 input.context.subagents.set(input.callId, subagent);
1984
1985 if (existing === undefined) {
1986 yield* emitProviderEvent({
1987 type: "app_thread.created",
1988 driver: CursorAgentSdk.CURSOR_PROVIDER,
1989 appThread: makeSubagentChildThread({
1990 parentThread: input.context.input.appThread,
1991 childThreadId,
1992 parentNodeId: nodeId,
1993 activeProviderThreadId: null,
1994 providerInstanceId: input.context.input.modelSelection.instanceId,
1995 modelSelection: input.context.input.modelSelection,
1996 title: subagentThreadTitle({
1997 parentTitle: input.context.input.appThread.title,
1998 title: args.description,
1999 prompt: args.prompt,
2000 ordinal: input.context.subagents.size,
2001 }),
2002 now,
2003 createdBy: "agent",
2004 creationSource: "provider",
2005 }),
2006 });
2007 const promptNativeId = `${nativeItemId}:prompt`;
2008 const promptArtifacts = makeSubagentConversationArtifacts({
2009 senderThreadId: input.context.input.threadId,
2010 messageId: idAllocator.derive.messageFromProviderItem({
2011 driver: CursorAgentSdk.CURSOR_PROVIDER,
2012 nativeItemId: promptNativeId,
2013 }),
2014 turnItemId: idAllocator.derive.turnItemFromProviderItem({
2015 driver: CursorAgentSdk.CURSOR_PROVIDER,
2016 nativeItemId: promptNativeId,
2017 }),
2018 threadId: childThreadId,
2019 rootNodeId: childRootNodeId,
2020 providerThreadId: null,
2021 providerTurnId: null,
2022 nativeItemRef: {
2023 driver: CursorAgentSdk.CURSOR_PROVIDER,
2024 nativeId: promptNativeId,
2025 strength: "weak",
2026 },
2027 role: "user",
2028 text: args.prompt,
2029 ordinal: 100,
2030 now,
2031 });
2032 yield* emitProviderEvent({
2033 type: "message.updated",
2034 driver: CursorAgentSdk.CURSOR_PROVIDER,
2035 message: promptArtifacts.message,
2036 });
2037 yield* emitProviderEvent({
2038 type: "turn_item.updated",
2039 driver: CursorAgentSdk.CURSOR_PROVIDER,
2040 turnItem: promptArtifacts.turnItem,
2041 });
2042 }
2043
2044 yield* emitProviderEvent({
2045 type: "node.updated",
2046 driver: CursorAgentSdk.CURSOR_PROVIDER,
2047 node: {
2048 id: nodeId,
2049 threadId: input.context.input.threadId,
2050 runId: input.context.input.runId,
2051 parentNodeId: input.context.input.rootNodeId,
2052 rootNodeId: input.context.input.rootNodeId,
2053 kind: "subagent",
2054 status,
2055 countsForRun: false,
2056 providerThreadId: input.context.input.providerThread.id,
2057 providerTurnId: input.context.providerTurnId,
2058 nativeItemRef: task.nativeTaskRef,
2059 runtimeRequestId: null,
2060 checkpointScopeId: null,
2061 startedAt: task.startedAt,
2062 completedAt: task.completedAt,
2063 },
2064 });
2065 yield* emitProviderEvent({
2066 type: "node.updated",
2067 driver: CursorAgentSdk.CURSOR_PROVIDER,
2068 node: {
2069 id: childRootNodeId,
2070 threadId: childThreadId,
2071 runId: null,
2072 parentNodeId: null,
2073 rootNodeId: childRootNodeId,
2074 kind: "root_turn",
2075 status,
2076 countsForRun: false,
2077 providerThreadId: null,
2078 providerTurnId: null,
2079 nativeItemRef: task.nativeTaskRef,
2080 runtimeRequestId: null,
2081 checkpointScopeId: null,
2082 startedAt: task.startedAt,
2083 completedAt: task.completedAt,
2084 },
2085 });
2086 yield* emitProviderEvent({
2087 type: "subagent.updated",
2088 driver: CursorAgentSdk.CURSOR_PROVIDER,
2089 subagent: task,
2090 });
2091 yield* emitProviderEvent({
2092 type: "turn_item.updated",
2093 driver: CursorAgentSdk.CURSOR_PROVIDER,
2094 turnItem: {
2095 id: subagent.turnItemId,
2096 threadId: input.context.input.threadId,
2097 runId: input.context.input.runId,
2098 nodeId,
2099 providerThreadId: input.context.input.providerThread.id,
2100 providerTurnId: input.context.providerTurnId,
2101 nativeItemRef: task.nativeTaskRef,
2102 parentItemId: null,
2103 ordinal: subagent.turnItemOrdinal,
2104 status,
2105 title: task.title,
2106 startedAt: task.startedAt,
2107 completedAt: task.completedAt,
2108 updatedAt: now,
2109 type: "subagent",
2110 subagentId: task.id,
2111 origin: task.origin,
2112 driver: task.driver,
2113 providerInstanceId: task.providerInstanceId,
2114 childThreadId,
2115 prompt: task.prompt,
2116 result: task.result,
2117 },
2118 });
2119
2120 if (input.completed && !subagent.resultProjected) {
2121 yield* completeSubagentReasoning(subagent);
2122 yield* completeSubagentAssistant(subagent);
2123 // A tool with neither a live completion nor a saved step has an unknown outcome.
2124 const unfinishedStatus =
2125 status === "interrupted" || status === "failed" || status === "cancelled"
2126 ? status
2127 : "interrupted";
2128 const savedTools = toolCallsFromConversationSteps(result?.conversationSteps ?? []);
2129 for (const tool of subagent.tools.values()) {
2130 const saved = savedTools.find(
2131 (nestedTool) => `${nativeItemId}:child-tool:${nestedTool.callId}` === tool.callId,
2132 );
2133 if (saved !== undefined) {
2134 tool.toolCall = saved.toolCall;
2135 }
2136 yield* emitToolArtifacts({
2137 active: tool,
2138 completed: true,
2139 ...(saved === undefined ? { unfinishedStatus } : {}),
2140 });
2141 }
2142 subagent.tools.clear();
2143 for (const [index, nestedTool] of savedTools.entries()) {
2144 if (subagent.liveToolCallIds.has(nestedTool.callId)) {
2145 continue;
2146 }
2147 const callId = `${nativeItemId}:child-tool:${nestedTool.callId || index + 1}`;
2148 const startedAt = task.startedAt ?? now;
2149 const active: ActiveCursorToolCall = {
2150 callId,
2151 toolCall: nestedTool.toolCall,
2152 target: childProjectionTarget(subagent),
2153 ordinal: ++subagent.nextChildOrdinal,
2154 startedAt,
2155 streamedOutput: "",
2156 };
2157 yield* emitToolArtifacts({ active, completed: true });
2158 }
2159 const unstreamedResult = resultParts
2160 .filter((part) => !subagent.streamedAssistantText.includes(part.trim()))
2161 .join("\n");
2162 if (unstreamedResult.length > 0) {
2163 const resultNativeId = `${nativeItemId}:result`;
2164 const resultArtifacts = makeSubagentConversationArtifacts({
2165 messageId: idAllocator.derive.messageFromProviderItem({
2166 driver: CursorAgentSdk.CURSOR_PROVIDER,
2167 nativeItemId: resultNativeId,
2168 }),
2169 turnItemId: idAllocator.derive.turnItemFromProviderItem({
2170 driver: CursorAgentSdk.CURSOR_PROVIDER,
2171 nativeItemId: resultNativeId,
2172 }),
2173 threadId: childThreadId,
2174 rootNodeId: childRootNodeId,
2175 providerThreadId: null,
2176 providerTurnId: null,
2177 nativeItemRef: {
2178 driver: CursorAgentSdk.CURSOR_PROVIDER,
2179 nativeId: resultNativeId,
2180 strength: "weak",
2181 },
2182 role: "assistant",
2183 text: unstreamedResult,
2184 ordinal: ++subagent.nextChildOrdinal,
2185 now,
2186 });
2187 yield* emitProviderEvent({
2188 type: "message.updated",
2189 driver: CursorAgentSdk.CURSOR_PROVIDER,
2190 message: resultArtifacts.message,
2191 });
2192 yield* emitProviderEvent({
2193 type: "turn_item.updated",
2194 driver: CursorAgentSdk.CURSOR_PROVIDER,
2195 turnItem: resultArtifacts.turnItem,
2196 });
2197 }
2198 subagent.resultProjected = true;
2199 }
2200 });
2201
2202 const appendSubagentText = Effect.fnUntraced(function* (input: {
2203 readonly subagent: ActiveCursorSubagent;
2204 readonly stream: ActiveCursorTextStream;
2205 readonly kind: "assistant" | "reasoning";
2206 readonly text: string;
2207 }) {
2208 if (input.stream.current === null) {
2209 input.stream.nextSegment += 1;
2210 input.stream.current = {
2211 nativeItemId: `${input.subagent.callId}:${input.kind}:${input.stream.nextSegment}`,
2212 startedAt: yield* DateTime.now,
2213 ordinal: ++input.subagent.nextChildOrdinal,
2214 text: "",
2215 };
2216 }
2217 input.stream.current.text += input.text;
2218 });
2219
2220 const completeSubagentAssistant = Effect.fnUntraced(function* (
2221 subagent: ActiveCursorSubagent,
2222 ) {
2223 if (subagent.assistant.current === null) {
2224 return;
2225 }
2226 yield* emitAssistant(childProjectionTarget(subagent), subagent.assistant.current, true);
2227 subagent.assistant.current = null;
2228 });
2229
2230 const completeSubagentReasoning = Effect.fnUntraced(function* (
2231 subagent: ActiveCursorSubagent,
2232 ) {
2233 if (subagent.reasoning.current === null) {
2234 return;
2235 }
2236 yield* emitReasoning(childProjectionTarget(subagent), subagent.reasoning.current, true);
2237 subagent.reasoning.current = null;
2238 });
2239
2240 const handleTaskUpdate = Effect.fnUntraced(function* (
2241 context: ActiveCursorTurn,
2242 update: Extract<InteractionUpdate, { readonly type: "tool-call-delta" }>,
2243 ) {
2244 const subagent = context.subagents.get(update.callId);
2245 if (subagent === undefined || !isOrchestrationV2WorkActive(subagent.task.status)) {
2246 return;
2247 }
2248 const taskUpdate = update.taskUpdate;
2249 switch (taskUpdate.type) {
2250 case "text-delta":
2251 subagent.streamedAssistantText += taskUpdate.text;
2252 yield* completeSubagentReasoning(subagent);
2253 yield* appendSubagentText({
2254 subagent,
2255 stream: subagent.assistant,
2256 kind: "assistant",
2257 text: taskUpdate.text,
2258 });
2259 yield* emitAssistant(
2260 childProjectionTarget(subagent),
2261 subagent.assistant.current,
2262 false,
2263 );
2264 return;
2265 case "thinking-delta":
2266 yield* completeSubagentAssistant(subagent);
2267 yield* appendSubagentText({
2268 subagent,
2269 stream: subagent.reasoning,
2270 kind: "reasoning",
2271 text: taskUpdate.text,
2272 });
2273 yield* emitReasoning(
2274 childProjectionTarget(subagent),
2275 subagent.reasoning.current,
2276 false,
2277 );
2278 return;
2279 case "thinking-completed":
2280 yield* completeSubagentReasoning(subagent);
2281 return;
2282 case "step-completed":
2283 yield* completeSubagentAssistant(subagent);
2284 yield* completeSubagentReasoning(subagent);
2285 return;
2286 case "tool-call-started":
2287 case "partial-tool-call":
2288 case "tool-call-completed": {
2289 subagent.liveToolCallIds.add(taskUpdate.callId);
2290 yield* completeSubagentAssistant(subagent);
2291 yield* completeSubagentReasoning(subagent);
2292 const nestedCallId = `${subagent.callId}:child-tool:${taskUpdate.callId}`;
2293 const completed = taskUpdate.type === "tool-call-completed";
2294 let active = subagent.tools.get(nestedCallId);
2295 if (active === undefined) {
2296 active = {
2297 callId: nestedCallId,
2298 toolCall: taskUpdate.toolCall,
2299 target: childProjectionTarget(subagent),
2300 ordinal: ++subagent.nextChildOrdinal,
2301 startedAt: yield* DateTime.now,
2302 streamedOutput: "",
2303 };
2304 subagent.tools.set(nestedCallId, active);
2305 yield* emitToolArtifacts({ active, completed: false });
2306 }
2307 active.toolCall = taskUpdate.toolCall;
2308 if (taskUpdate.type !== "tool-call-started") {
2309 yield* emitToolArtifacts({ active, completed });
2310 }
2311 if (completed) {
2312 subagent.tools.delete(nestedCallId);
2313 }
2314 return;
2315 }
2316 default:
2317 return;
2318 }
2319 });
2320
2321 const handleToolUpdate = Effect.fnUntraced(function* (
2322 context: ActiveCursorTurn,
2323 update: Extract<
2324 InteractionUpdate,
2325 {
2326 readonly type: "tool-call-started" | "partial-tool-call" | "tool-call-completed";
2327 }
2328 >,
2329 ) {
2330 const completed = update.type === "tool-call-completed";
2331 const toolCall = update.toolCall;
2332 switch (toolCall.type) {
2333 case "createPlan":
2334 yield* emitPlanArtifacts({
2335 context,
2336 callId: update.callId,
2337 markdown: toolCall.args.plan,
2338 completed,
2339 failed: completed && cursorToolFailed(toolCall),
2340 });
2341 return;
2342 case "updateTodos":
2343 yield* emitTodoArtifacts({
2344 context,
2345 callId: update.callId,
2346 toolCall,
2347 completed,
2348 failed: completed && cursorToolFailed(toolCall),
2349 });
2350 return;
2351 case "task":
2352 if (update.type === "partial-tool-call") {
2353 return;
2354 }
2355 yield* emitSubagent({
2356 context,
2357 callId: update.callId,
2358 toolCall,
2359 completed,
2360 });
2361 return;
2362 default: {
2363 const active = yield* ensureToolStarted(context, update.callId, toolCall);
2364 active.toolCall = toolCall;
2365 if (update.type !== "tool-call-started") {
2366 yield* emitToolArtifacts({ active, completed });
2367 }
2368 if (completed) {
2369 context.tools.delete(update.callId);
2370 }
2371 }
2372 }
2373 });
2374
2375 const shellOutputText = (event: Record<string, unknown>): string => {
2376 if (event.case !== "stdout" && event.case !== "stderr") return "";
2377 const value = event.value;
2378 if (typeof value !== "object" || value === null || !("data" in value)) return "";
2379 return typeof value.data === "string" ? value.data : "";
2380 };
2381
2382 const handleInteractionUpdate = Effect.fnUntraced(function* (
2383 context: ActiveCursorTurn,
2384 update: InteractionUpdate,
2385 ) {
2386 if (context.finalized) {
2387 return;
2388 }
2389 if (update.type === "turn-ended") {
2390 context.turnEnded = true;
2391 if (update.usage !== undefined) {
2392 context.usage = addCursorTurnUsage(context.usage, update.usage);
2393 }
2394 } else if (
2395 update.type === "step-started" ||
2396 update.type === "user-message-appended" ||
2397 update.type === "text-delta" ||
2398 update.type === "thinking-delta" ||
2399 update.type === "partial-tool-call" ||
2400 update.type === "tool-call-started" ||
2401 update.type === "tool-call-delta"
2402 ) {
2403 context.turnEnded = false;
2404 }
2405 switch (update.type) {
2406 case "text-delta":
2407 // Classify each assistant message on its own, so earlier
2408 // commentary does not hide a later standalone transport dump.
2409 if (context.assistant.current === null) {
2410 context.assistantReply = new CursorTransportFailure();
2411 }
2412 context.assistantReply.push(update.text);
2413 yield* completeReasoning(context);
2414 yield* appendTextSegment({
2415 context,
2416 stream: context.assistant,
2417 kind: "assistant",
2418 text: update.text,
2419 });
2420 yield* emitAssistant(parentTarget(context), context.assistant.current, false);
2421 return;
2422 case "thinking-delta":
2423 yield* completeAssistant(context);
2424 yield* appendTextSegment({
2425 context,
2426 stream: context.reasoning,
2427 kind: "reasoning",
2428 text: update.text,
2429 });
2430 yield* emitReasoning(parentTarget(context), context.reasoning.current, false);
2431 return;
2432 case "thinking-completed":
2433 yield* completeReasoning(context);
2434 return;
2435 case "tool-call-started":
2436 case "partial-tool-call":
2437 case "tool-call-completed":
2438 yield* completeAssistant(context);
2439 yield* completeReasoning(context);
2440 yield* handleToolUpdate(context, update);
2441 return;
2442 case "tool-call-delta":
2443 yield* handleTaskUpdate(context, update);
2444 return;
2445 case "step-completed":
2446 case "turn-ended":
2447 yield* completeAssistant(context);
2448 yield* completeReasoning(context);
2449 return;
2450 case "summary-completed":
2451 if (update.failed !== true) {
2452 context.compacted = true;
2453 yield* Ref.set(told, {
2454 agent: context.run.agentId,
2455 orchestration: false,
2456 device: false,
2457 backgroundWait: false,
2458 runtime: undefined,
2459 });
2460 yield* Ref.update(interruptedPrompt, (current) =>
2461 current?.agent === context.run.agentId
2462 ? { ...current, runtimeInstructions: undefined }
2463 : current,
2464 );
2465 }
2466 return;
2467 case "shell-output-delta": {
2468 const toolCallId = update.event.toolCallId;
2469 const shell =
2470 typeof toolCallId === "string"
2471 ? context.tools.get(toolCallId)
2472 : Array.from(context.tools.values())
2473 .toReversed()
2474 .find((candidate) => candidate.toolCall.type === "shell");
2475 if (shell?.toolCall.type !== "shell") {
2476 return;
2477 }
2478 const chunk = shellOutputText(update.event);
2479 if (chunk.length === 0) return;
2480 // Persist output once; live hub deltas avoid quadratic event-store growth.
2481 shell.streamedOutput += chunk;
2482 // Trimming on every chunk would flatten and copy the whole tail each time.
2483 if (shell.streamedOutput.length > 2 * MAX_CURSOR_STREAMED_OUTPUT_CHARS) {
2484 shell.streamedOutput = shell.streamedOutput.slice(
2485 -MAX_CURSOR_STREAMED_OUTPUT_CHARS,
2486 );
2487 }
2488 yield* emitProviderEvent({
2489 type: "command_output.delta",
2490 driver: CursorAgentSdk.CURSOR_PROVIDER,
2491 threadId: shell.target.threadId,
2492 itemId: idAllocator.derive.turnItemFromProviderItem({
2493 driver: CursorAgentSdk.CURSOR_PROVIDER,
2494 nativeItemId: shell.callId,
2495 }),
2496 chunk,
2497 });
2498 return;
2499 }
2500 default:
2501 return;
2502 }
2503 });
2504
2505 const providerTurnPayload = (input: {
2506 readonly context: ActiveCursorTurn;
2507 readonly status: OrchestrationV2ProviderTurn["status"];
2508 readonly completedAt: DateTime.Utc | null;
2509 readonly tokenUsage?: OrchestrationV2ProviderTurn["tokenUsage"];
2510 }): OrchestrationV2ProviderTurn => ({
2511 id: input.context.providerTurnId,
2512 providerThreadId: input.context.input.providerThread.id,
2513 nodeId: input.context.input.rootNodeId,
2514 runAttemptId: input.context.input.attemptId,
2515 nativeTurnRef: {
2516 driver: CursorAgentSdk.CURSOR_PROVIDER,
2517 nativeId: input.context.run.runId,
2518 strength: "strong",
2519 },
2520 ordinal: input.context.input.providerTurnOrdinal,
2521 status: input.status,
2522 startedAt: input.context.startedAt,
2523 completedAt: input.completedAt,
2524 ...(input.tokenUsage === undefined ? {} : { tokenUsage: input.tokenUsage }),
2525 ...(input.completedAt === null || input.context.usage === undefined
2526 ? {}
2527 : {
2528 turnTokenUsage: {
2529 usageScope: "main_agent",
2530 usageStatus: input.status === "completed" ? "complete" : "partial",
2531 // Cursor's inputTokens already include cache reads and writes.
2532 inputTokens: input.context.usage.inputTokens,
2533 cachedInputTokens: input.context.usage.cacheReadTokens,
2534 cacheCreationTokens: input.context.usage.cacheWriteTokens,
2535 outputTokens: input.context.usage.outputTokens,
2536 ...(input.context.usage.reasoningTokens === undefined
2537 ? {}
2538 : { reasoningTokens: input.context.usage.reasoningTokens }),
2539 hasSubagents: input.context.subagents.size > 0,
2540 },
2541 }),
2542 });
2543
2544 const finalizeTurn = Effect.fnUntraced(function* (input: {
2545 readonly context: ActiveCursorTurn;
2546 readonly status: Extract<
2547 OrchestrationV2ProviderTurn["status"],
2548 "completed" | "interrupted" | "failed" | "cancelled"
2549 >;
2550 readonly failure?: OrchestrationV2ProviderFailure;
2551 readonly threadDisposition?: "reusable" | "broken";
2552 }) {
2553 if (input.context.finalized) {
2554 return;
2555 }
2556 input.context.finalized = true;
2557 const completedAt = yield* DateTime.now;
2558 for (const tool of input.context.tools.values()) {
2559 yield* emitToolArtifacts({
2560 active: tool,
2561 completed: true,
2562 // No completion event means the tool outcome is unknown.
2563 unfinishedStatus: input.status === "completed" ? "interrupted" : input.status,
2564 });
2565 }
2566 input.context.tools.clear();
2567 for (const subagent of input.context.subagents.values()) {
2568 if (!isOrchestrationV2WorkActive(subagent.task.status)) continue;
2569 yield* emitSubagent({
2570 context: input.context,
2571 callId: subagent.callId,
2572 toolCall: subagent.toolCall,
2573 completed: true,
2574 status: input.status === "completed" ? "idle" : input.status,
2575 });
2576 }
2577 yield* completeReasoning(input.context);
2578 yield* completeAssistant(input.context);
2579 // The turn's billed totals count every step; only the checkpoint knows the context fill.
2580 const contextUsage = yield* (
2581 input.context.session.readContextUsage ?? Effect.undefined
2582 ).pipe(
2583 Effect.catch((cause) =>
2584 Effect.logWarning("orchestration-v2.cursor-context-usage-unavailable", {
2585 providerTurnId: input.context.providerTurnId,
2586 cause,
2587 }).pipe(Effect.as(undefined)),
2588 ),
2589 );
2590 yield* emitProviderEvent({
2591 type: "provider_turn.updated",
2592 driver: CursorAgentSdk.CURSOR_PROVIDER,
2593 providerTurn: providerTurnPayload({
2594 context: input.context,
2595 status: input.status,
2596 completedAt,
2597 ...(contextUsage === undefined
2598 ? {}
2599 : {
2600 tokenUsage: {
2601 usedTokens: contextUsage.usedTokens,
2602 maxTokens: contextUsage.maxTokens,
2603 updatedAt: DateTime.formatIso(completedAt),
2604 },
2605 }),
2606 }),
2607 });
2608 yield* emitProviderThread({
2609 ...input.context.input.providerThread,
2610 providerSessionId: session.id,
2611 status: "active",
2612 firstRunOrdinal:
2613 input.context.input.providerThread.firstRunOrdinal ?? input.context.input.runOrdinal,
2614 lastRunOrdinal: input.context.input.runOrdinal,
2615 updatedAt: completedAt,
2616 });
2617 const threadDisposition = input.threadDisposition ?? "reusable";
2618 yield* emitProviderEvent(
2619 input.status === "failed"
2620 ? {
2621 type: "turn.terminal",
2622 driver: CursorAgentSdk.CURSOR_PROVIDER,
2623 providerThreadId: input.context.input.providerThread.id,
2624 providerTurnId: input.context.providerTurnId,
2625 runOrdinal: input.context.input.runOrdinal,
2626 failureItemOrdinal: yield* resolveItemOrdinal(
2627 input.context,
2628 `terminal-failure:${input.context.providerTurnId}`,
2629 ),
2630 status: input.status,
2631 failure: input.failure ?? makeProviderFailure({ class: "provider_error" }),
2632 threadDisposition,
2633 }
2634 : {
2635 type: "turn.terminal",
2636 driver: CursorAgentSdk.CURSOR_PROVIDER,
2637 providerThreadId: input.context.input.providerThread.id,
2638 providerTurnId: input.context.providerTurnId,
2639 runOrdinal: input.context.input.runOrdinal,
2640 status: input.status,
2641 failure: null,
2642 threadDisposition,
2643 },
2644 );
2645 if (input.context.runtimeInstructions !== undefined) {
2646 const deliveredRuntime =
2647 input.status === "completed" && !input.context.compacted
2648 ? input.context.runtimeInstructions
2649 : undefined;
2650 yield* Ref.update(told, (current) =>
2651 current?.agent === input.context.run.agentId
2652 ? { ...current, runtime: deliveredRuntime }
2653 : current,
2654 );
2655 }
2656 if (input.status === "interrupted" && input.context.prompt !== undefined) {
2657 yield* Ref.set(interruptedPrompt, {
2658 agent: input.context.run.agentId,
2659 runId: input.context.run.runId,
2660 text: input.context.prompt,
2661 message: input.context.message,
2662 runtimeInstructions: input.context.compacted
2663 ? undefined
2664 : input.context.runtimeInstructions,
2665 });
2666 }
2667 yield* Ref.update(activeTurn, (current) =>
2668 current?.providerTurnId === input.context.providerTurnId ? null : current,
2669 );
2670 yield* Deferred.succeed(input.context.completed, undefined);
2671 });
2672
2673 const isResumeFailureAfterTurnEnded = (context: ActiveCursorTurn, result: RunResult) =>
2674 context.turnEnded &&
2675 result.status === "error" &&
2676 result.error?.message === CURSOR_RESUME_NO_PROGRESS_MESSAGE;
2677
2678 const terminalStatus = (
2679 context: ActiveCursorTurn,
2680 result: RunResult,
2681 ): Extract<
2682 OrchestrationV2ProviderTurn["status"],
2683 "completed" | "interrupted" | "failed" | "cancelled"
2684 > => {
2685 if (context.interrupted) {
2686 return "interrupted";
2687 }
2688 switch (result.status) {
2689 case "finished":
2690 return "completed";
2691 case "cancelled":
2692 return "cancelled";
2693 case "error":
2694 return isResumeFailureAfterTurnEnded(context, result) ? "completed" : "failed";
2695 }
2696 };
2697
2698 const resolveWorkspaceMcpServers = (cwd: string | null) =>
2699 cwd === null
2700 ? Effect.succeed({})
2701 : cursorWorkspaceMcpServers(cwd, adapterOptions.environment).pipe(
2702 Effect.provideService(FileSystem.FileSystem, fileSystem),
2703 Effect.provideService(Path.Path, path),
2704 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
2705 // Unreadable Cursor state leaves startup to the SDK rather than failing the turn.
2706 Effect.catch((cause) =>
2707 Effect.logWarning("orchestration-v2.cursor-workspace-mcp-unresolved", {
2708 cwd,
2709 cause,
2710 }).pipe(Effect.as({})),
2711 ),
2712 );
2713
2714 const openAgent = Effect.fnUntraced(function* (openInput: {
2715 readonly operation: "create" | "resume";
2716 readonly threadId: ThreadId;
2717 readonly modelSelection: ModelSelection;
2718 readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
2719 readonly agentId?: string;
2720 readonly storeCwd?: string | undefined;
2721 }) {
2722 const existing = yield* Ref.get(liveAgent);
2723 const cwd = openInput.runtimePolicy.cwd ?? process.cwd();
2724 const storeCwd =
2725 openInput.storeCwd ??
2726 (openInput.operation === "resume"
2727 ? existing !== null && existing.nativeThreadId === openInput.agentId
2728 ? existing.storeCwd
2729 : input.resumeFromSession?.cwd
2730 : undefined) ??
2731 cwd;
2732 if (
2733 existing !== null &&
2734 openInput.operation === "resume" &&
2735 existing.nativeThreadId === openInput.agentId &&
2736 existing.session.isAlive?.() !== false
2737 ) {
2738 return existing;
2739 }
2740 if (existing !== null) {
2741 yield* existing.session.close.pipe(Effect.ignore);
2742 yield* Ref.set(liveAgent, null);
2743 }
2744 const options = makeCursorAgentOptions({
2745 ...(apiKey === undefined ? {} : { apiKey }),
2746 modelSelection: openInput.modelSelection,
2747 models: adapterOptions.getModels?.() ?? [],
2748 sdkModels: adapterOptions.getSdkModels?.() ?? [],
2749 runtimePolicy: openInput.runtimePolicy,
2750 platform,
2751 threadId: openInput.threadId,
2752 mcpSession: yield* mcpSessions.read(openInput.threadId),
2753 });
2754 if (
2755 platform === "win32" &&
2756 openInput.runtimePolicy.sandboxPolicy === undefined &&
2757 openInput.runtimePolicy.runtimeMode !== "full-access" &&
2758 options.local?.sandboxOptions?.enabled === false &&
2759 !(yield* Ref.getAndSet(warnedUnsupportedSandbox, true))
2760 ) {
2761 yield* Effect.logWarning(
2762 "Cursor cannot sandbox the filesystem on Windows; this thread runs without filesystem isolation.",
2763 );
2764 }
2765 const sdkSession = yield* runner
2766 .open({
2767 operation: openInput.operation,
2768 ...(openInput.agentId === undefined ? {} : { agentId: openInput.agentId }),
2769 storeCwd,
2770 options,
2771 threadId: openInput.threadId,
2772 providerSessionId: input.providerSessionId,
2773 })
2774 .pipe(Effect.mapError(classifyCursorModelRejection(openInput.modelSelection)));
2775 const next = {
2776 nativeThreadId: sdkSession.agentId,
2777 storeCwd,
2778 session: sdkSession,
2779 } satisfies CursorLiveAgent;
2780 yield* Ref.set(liveAgent, next);
2781 return next;
2782 });
2783
2784 let cursorSkills: ReadonlyMap<string, ServerProviderSkill> | undefined;
2785 const resolveCursorSkillText = Effect.fn("CursorAdapterV2.resolveCursorSkillText")(
2786 function* (rawText: string, cwd: string | undefined) {
2787 if (
2788 cursorSkills === undefined &&
2789 (hasCursorSkillMention(rawText) || cursorSlashSkillNames(rawText).size > 0)
2790 ) {
2791 const skills = yield* discoverCursorSkills(cwd, adapterOptions.environment).pipe(
2792 Effect.provideService(FileSystem.FileSystem, fileSystem),
2793 Effect.provideService(Path.Path, path),
2794 );
2795 cursorSkills = new Map(
2796 skills
2797 .filter((skill) => skill.enabled && skill.userInvocable !== false)
2798 .map((skill) => [skill.name, skill]),
2799 );
2800 }
2801 if (cursorSkills === undefined) return rawText;
2802 const skillsByName = cursorSkills;
2803 const text = rewriteCursorSkillMentions(rawText, new Set(skillsByName.keys()));
2804 const invoked = yield* Effect.forEach(cursorSlashSkillNames(text), (name) => {
2805 const skill = skillsByName.get(name);
2806 return skill?.userInvocationOnly === true
2807 ? fileSystem.readFileString(skill.path).pipe(
2808 Effect.map((contents) => [{ name, contents }]),
2809 Effect.orElseSucceed(() => []),
2810 )
2811 : Effect.succeed([]);
2812 });
2813 return appendCursorInvokedSkills(text, invoked.flat());
2814 },
2815 );
2816 const resolveUserMessage = Effect.fnUntraced(function* (
2817 turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
2818 mcpServers: Record<string, McpServerConfig> | undefined,
2819 hasDeviceTools: boolean,
2820 delivered: {
2821 readonly orchestration: boolean;
2822 readonly device: boolean;
2823 readonly backgroundWait: boolean;
2824 readonly runtime: string | undefined;
2825 },
2826 interrupted: string | undefined,
2827 ) {
2828 const rawText = turnInput.message.text;
2829 if (rawText.trim() === "/compress" && turnInput.message.attachments.length === 0) {
2830 return { message: "/compress", prompt: undefined, runtimeInstructions: undefined };
2831 }
2832 const newText = t3OrchestrationPrompt({
2833 prompt: yield* providerMessageTextWithAttachmentPaths({
2834 text: yield* resolveCursorSkillText(
2835 rawText,
2836 turnInput.runtimePolicy.cwd ?? undefined,
2837 ),
2838 attachments: turnInput.message.attachments,
2839 resolveAttachmentPath: host.resolveAttachmentPath,
2840 resolveExtractedTextPath: host.resolveExtractedTextPath,
2841 }),
2842 hasT3Mcp: mcpServers !== undefined,
2843 hasDeviceTools,
2844 orchestrationDelivered: delivered.orchestration,
2845 deviceInstructionsDelivered: delivered.device,
2846 providerInstructions: CURSOR_BACKGROUND_WAIT_INSTRUCTIONS,
2847 providerInstructionsDelivered: delivered.backgroundWait,
2848 });
2849 const userText =
2850 interrupted === undefined
2851 ? newText
2852 : `Your previous turn was interrupted and is missing from your history. Some of its work may already be done. Its request was:\n\n${interrupted}\n\nThe new message, which may continue or change that request:\n\n${newText}`;
2853 const images = yield* Effect.forEach(
2854 turnInput.message.attachments.filter(isProviderNativeImageAttachment),
2855 (attachment: ChatAttachment) =>
2856 Effect.gen(function* () {
2857 const path = host.resolveAttachmentPath(attachment);
2858 if (path === null) {
2859 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
2860 driver: CursorAgentSdk.CURSOR_PROVIDER,
2861 detail: `Invalid attachment id '${attachment.id}'.`,
2862 });
2863 }
2864 const bytes = yield* fileSystem.readFile(path).pipe(
2865 Effect.mapError(
2866 (cause) =>
2867 new ProviderAdapter.ProviderAdapterProtocolError({
2868 driver: CursorAgentSdk.CURSOR_PROVIDER,
2869 detail: `Failed to read attachment '${attachment.id}'.`,
2870 reason: "attachment_unreadable",
2871 payload: cause,
2872 }),
2873 ),
2874 );
2875 return {
2876 data: Buffer.from(bytes).toString("base64"),
2877 mimeType: attachment.mimeType,
2878 };
2879 }),
2880 { concurrency: 1 },
2881 );
2882 if (userText.length === 0 && images.length === 0) {
2883 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
2884 driver: CursorAgentSdk.CURSOR_PROVIDER,
2885 detail: "Cursor turn requires non-empty text or attachments.",
2886 });
2887 }
2888 const runtimeInstructions = buildRuntimeInstructions({
2889 harness: "Cursor",
2890 model: turnInput.modelSelection.model,
2891 });
2892 // Resend only on a new/compacted/rewound conversation or when the model changes.
2893 const sendRuntimeInstructions = delivered.runtime !== runtimeInstructions;
2894 const text = sendRuntimeInstructions
2895 ? userText.length === 0
2896 ? runtimeInstructions
2897 : `${userText}\n\n${runtimeInstructions}`
2898 : userText;
2899 return {
2900 message: images.length === 0 ? text : ({ text, images } satisfies SDKUserMessage),
2901 prompt: userText,
2902 runtimeInstructions: sendRuntimeInstructions ? runtimeInstructions : undefined,
2903 };
2904 });
2905
2906 const startTurn = Effect.fn("CursorAdapterV2.startTurn")(
2907 function* (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) {
2908 const current = yield* Ref.get(activeTurn);
2909 if (current !== null) {
2910 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
2911 driver: CursorAgentSdk.CURSOR_PROVIDER,
2912 detail: `Cursor provider turn ${current.providerTurnId} is still active.`,
2913 reason: "previous_turn_active",
2914 });
2915 }
2916 const agentId = nativeThreadId(turnInput.providerThread);
2917 const agent = yield* openAgent({
2918 operation: "resume",
2919 agentId,
2920 storeCwd: turnInput.providerThread.nativeMetadata?.cursorStoreCwd,
2921 threadId: turnInput.threadId,
2922 modelSelection: turnInput.modelSelection,
2923 runtimePolicy: turnInput.runtimePolicy,
2924 });
2925 const mcpSession = yield* mcpSessions.read(turnInput.threadId);
2926 const mcpServers = cursorMcpServers(mcpSession);
2927 const hasDeviceTools =
2928 mcpServers !== undefined && mcpSession?.capabilities?.has("device") === true;
2929 const known = yield* Ref.get(told);
2930 // A conversation this process has not sent to was told on its first run.
2931 const delivered =
2932 known?.agent === agent.nativeThreadId
2933 ? known
2934 : {
2935 orchestration: turnInput.nativeThreadHasTurns ?? turnInput.runOrdinal > 1,
2936 device: false,
2937 backgroundWait: false,
2938 runtime: undefined,
2939 };
2940 const interrupted = yield* Ref.get(interruptedPrompt);
2941 const runCheckpointed = (runId?: string) =>
2942 agent.session.runCheckpointed?.(runId) ?? Effect.succeed(false);
2943 const dropped =
2944 interrupted?.agent === agent.nativeThreadId &&
2945 !(yield* runCheckpointed(interrupted.runId))
2946 ? interrupted
2947 : undefined;
2948 // Cursor's ResumeAction continues from the latest checkpoint, which only holds a stopped
2949 // request once that run checkpointed; an earlier stop replays the request it dropped.
2950 const resume =
2951 turnInput.resume !== true
2952 ? undefined
2953 : dropped !== undefined
2954 ? ("replay" as const)
2955 : interrupted?.agent === agent.nativeThreadId ||
2956 (yield* Ref.get(resumedAgent)) === agent.nativeThreadId ||
2957 (yield* runCheckpointed())
2958 ? ("native" as const)
2959 : undefined;
2960 if (turnInput.resume === true && resume === undefined) {
2961 return yield* new ProviderAdapter.ProviderResumeUnsupportedError({
2962 driver: CursorAgentSdk.CURSOR_PROVIDER,
2963 providerThreadId: turnInput.providerThread.id,
2964 });
2965 }
2966 const { message, prompt, runtimeInstructions } =
2967 resume === "native"
2968 ? {
2969 message: "",
2970 prompt: undefined,
2971 runtimeInstructions:
2972 interrupted?.agent === agent.nativeThreadId
2973 ? interrupted.runtimeInstructions
2974 : undefined,
2975 }
2976 : resume === "replay"
2977 ? {
2978 message: dropped!.message,
2979 prompt: dropped!.text,
2980 runtimeInstructions: dropped!.runtimeInstructions,
2981 }
2982 : yield* resolveUserMessage(
2983 turnInput,
2984 mcpServers,
2985 hasDeviceTools,
2986 delivered,
2987 dropped?.text,
2988 );
2989 const compacted = resume === undefined && prompt === undefined;
2990 const pendingUpdates: Array<InteractionUpdate> = [];
2991 let context: ActiveCursorTurn | null = null;
2992 // A send-time set replaces the create-time set, so the workspace servers go only here and are
2993 // read again each turn from mcp.json and mcp-disabled.json; both merge with settingSources.
2994 const turnMcpServers = {
2995 ...(yield* resolveWorkspaceMcpServers(turnInput.runtimePolicy.cwd)),
2996 ...mcpServers,
2997 };
2998 const sdkRun = yield* agent.session
2999 .send({
3000 message,
3001 summarize: compacted,
3002 resume: resume === "native",
3003 options: {
3004 model: cursorSdkModelSelection(
3005 turnInput.modelSelection,
3006 adapterOptions.getModels?.() ?? [],
3007 adapterOptions.getSdkModels?.() ?? [],
3008 ),
3009 mode: turnInput.runtimePolicy.interactionMode === "plan" ? "plan" : "agent",
3010 ...(Object.keys(turnMcpServers).length === 0
3011 ? {}
3012 : { mcpServers: turnMcpServers }),
3013 },
3014 onDelta: (update) => {
3015 if (context === null) {
3016 return Effect.sync(() => {
3017 pendingUpdates.push(update);
3018 });
3019 }
3020 return handleInteractionUpdate(context, update);
3021 },
3022 onBackgroundShell: (shell) => onBackgroundShell(turnInput, shell),
3023 })
3024 .pipe(Effect.mapError(classifyCursorModelRejection(turnInput.modelSelection)));
3025 // A resume sends no new instructions, and a native one still continues the stopped request.
3026 if (resume === undefined) {
3027 yield* Ref.set(told, {
3028 agent: agent.nativeThreadId,
3029 orchestration: !compacted && (delivered.orchestration || mcpServers !== undefined),
3030 device: !compacted && hasDeviceTools,
3031 backgroundWait:
3032 !compacted && (delivered.backgroundWait || mcpServers !== undefined),
3033 runtime: compacted ? undefined : delivered.runtime,
3034 });
3035 }
3036 if (!compacted && resume !== "native") {
3037 yield* Ref.set(interruptedPrompt, null);
3038 }
3039 if (!compacted) {
3040 yield* Ref.set(resumedAgent, resume === "native" ? agent.nativeThreadId : null);
3041 }
3042 const startedAt = yield* DateTime.now;
3043 const completed = yield* Deferred.make<void, never>();
3044 const providerTurnId = idAllocator.derive.providerTurn({
3045 driver: CursorAgentSdk.CURSOR_PROVIDER,
3046 nativeTurnId: sdkRun.runId,
3047 });
3048 context = {
3049 input: turnInput,
3050 run: sdkRun,
3051 providerTurnId,
3052 startedAt,
3053 completed,
3054 itemOrdinals: new Map(),
3055 tools: new Map(),
3056 subagents: new Map(),
3057 assistant: {
3058 current: null,
3059 nextSegment: 0,
3060 },
3061 assistantReply: new CursorTransportFailure(),
3062 reasoning: {
3063 current: null,
3064 nextSegment: 0,
3065 },
3066 prompt,
3067 message,
3068 runtimeInstructions,
3069 compacted,
3070 interrupted: false,
3071 finalized: false,
3072 turnEnded: false,
3073 session: agent.session,
3074 usage: undefined,
3075 };
3076 yield* Ref.set(activeTurn, context);
3077 latestRunId = turnInput.runId;
3078 yield* emitProviderEvent({
3079 type: "provider_turn.updated",
3080 driver: CursorAgentSdk.CURSOR_PROVIDER,
3081 providerTurn: providerTurnPayload({
3082 context,
3083 status: "running",
3084 completedAt: null,
3085 }),
3086 });
3087 yield* emitProviderThread({
3088 ...turnInput.providerThread,
3089 providerSessionId: session.id,
3090 status: "active",
3091 updatedAt: startedAt,
3092 });
3093 for (const update of pendingUpdates) {
3094 yield* handleInteractionUpdate(context, update);
3095 }
3096
3097 yield* sdkRun.wait.pipe(
3098 Effect.flatMap((result) =>
3099 Effect.gen(function* () {
3100 if (
3101 context !== null &&
3102 context.assistant.nextSegment === 0 &&
3103 // A summarize run's result is the summary, not an answer.
3104 !compacted &&
3105 // Text from a resume that made no progress is not the turn's answer.
3106 !isResumeFailureAfterTurnEnded(context, result) &&
3107 result.result !== undefined &&
3108 result.result.length > 0
3109 ) {
3110 context.assistantReply.push(result.result);
3111 yield* appendTextSegment({
3112 context,
3113 stream: context.assistant,
3114 kind: "assistant",
3115 text: result.result,
3116 });
3117 }
3118 if (context !== null && isResumeFailureAfterTurnEnded(context, result)) {
3119 yield* Effect.logWarning(
3120 "orchestration-v2.cursor-resume-failed-after-turn-ended",
3121 {
3122 providerSessionId: input.providerSessionId,
3123 providerThreadId: turnInput.providerThread.id,
3124 providerTurnId,
3125 },
3126 );
3127 }
3128 if (context !== null) {
3129 const transportFailure = context.assistantReply.failure;
3130 const status =
3131 transportFailure === undefined ? terminalStatus(context, result) : "failed";
3132 yield* finalizeTurn({
3133 context,
3134 status,
3135 ...(status === "failed"
3136 ? {
3137 failure:
3138 transportFailure === undefined
3139 ? makeProviderFailure({
3140 cause: result.error,
3141 // makeProviderFailure never reads a cause's own text.
3142 message: result.error?.message,
3143 class: CursorAgentSdk.isCursorUsageLimitError(result.error)
3144 ? "usage_limit"
3145 : "provider_error",
3146 })
3147 : makeProviderFailure({
3148 message: transportFailure,
3149 class: "transport_error",
3150 }),
3151 }
3152 : {}),
3153 });
3154 }
3155 }),
3156 ),
3157 Effect.catch((cause) =>
3158 Effect.gen(function* () {
3159 if (context !== null) {
3160 yield* finalizeTurn({
3161 context,
3162 status: context.interrupted ? "interrupted" : "failed",
3163 ...(context.interrupted
3164 ? {}
3165 : {
3166 failure: makeProviderFailure({
3167 cause,
3168 message: CursorAgentSdk.isCursorAgentSdkRunnerError(cause)
3169 ? CursorAgentSdk.cursorSdkFailureMessage(cause)
3170 : undefined,
3171 class: CursorAgentSdk.isCursorUsageLimitError(cause)
3172 ? "usage_limit"
3173 : "transport_error",
3174 }),
3175 }),
3176 });
3177 }
3178 yield* Effect.logWarning("orchestration-v2.cursor-run-failed", {
3179 providerSessionId: input.providerSessionId,
3180 providerThreadId: turnInput.providerThread.id,
3181 providerTurnId,
3182 cause,
3183 });
3184 }),
3185 ),
3186 Effect.forkIn(sessionScope),
3187 );
3188 },
3189 (effect, turnInput) =>
3190 effect.pipe(
3191 Effect.mapError(
3192 (cause) =>
3193 new ProviderAdapter.ProviderAdapterTurnStartError({
3194 driver: CursorAgentSdk.CURSOR_PROVIDER,
3195 threadId: turnInput.threadId,
3196 providerThreadId: turnInput.providerThread.id,
3197 runId: turnInput.runId,
3198 cause,
3199 }),
3200 ),
3201 ),
3202 );
3203
3204 const closeSession = Effect.fnUntraced(function* () {
3205 yield* stopBackgroundShells();
3206 const existing = yield* Ref.get(liveAgent);
3207 if (existing !== null) {
3208 yield* existing.session.close.pipe(Effect.ignore);
3209 yield* Ref.set(liveAgent, null);
3210 }
3211 yield* runner.assertComplete.pipe(
3212 Effect.catchCause((cause) =>
3213 Effect.logWarning("orchestration-v2.cursor-runner-incomplete", {
3214 providerSessionId: input.providerSessionId,
3215 cause,
3216 }),
3217 ),
3218 );
3219 });
3220 yield* Effect.addFinalizer(() => closeSession());
3221
3222 const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = {
3223 instanceId: adapterOptions.instanceId,
3224 driver: CursorAgentSdk.CURSOR_PROVIDER,
3225 providerSessionId: input.providerSessionId,
3226 providerSession: session,
3227 getModelContextWindow: (selection) =>
3228 selection.instanceId === adapterOptions.instanceId
3229 ? cursorContextWindowTokens(selection, adapterOptions.getModels?.() ?? [])
3230 : undefined,
3231 events: Stream.fromEffectRepeat(Queue.take(events)),
3232 // closeSession stops every shell, so idle release must wait while any still runs.
3233 backgroundTasksEndWithProcess: true,
3234 hasPendingBackgroundWork: Effect.sync(() => backgroundShells.size > 0),
3235 hasPendingBackgroundWorkForThread: (providerThread) =>
3236 Effect.sync(() =>
3237 [...backgroundShells.values()].some(
3238 (shell) => shell.providerThreadId === providerThread.id,
3239 ),
3240 ),
3241 ensureThread: Effect.fn("CursorAdapterV2.ensureThread")(
3242 function* (threadInput: ProviderAdapter.ProviderAdapterV2EnsureThreadInput) {
3243 const opened = yield* openAgent({
3244 operation: "create",
3245 threadId: threadInput.threadId,
3246 modelSelection: threadInput.modelSelection,
3247 runtimePolicy: threadInput.runtimePolicy,
3248 });
3249 const now = yield* DateTime.now;
3250 return makeProviderThread({
3251 idAllocator,
3252 providerInstanceId: adapterOptions.instanceId,
3253 appThreadId: threadInput.threadId,
3254 providerSessionId: input.providerSessionId,
3255 nativeThreadId: opened.nativeThreadId,
3256 storeCwd: opened.storeCwd,
3257 now,
3258 });
3259 },
3260 (effect, threadInput) =>
3261 effect.pipe(
3262 Effect.mapError(
3263 (cause) =>
3264 new ProviderAdapter.ProviderAdapterEnsureThreadError({
3265 driver: CursorAgentSdk.CURSOR_PROVIDER,
3266 threadId: threadInput.threadId,
3267 cause,
3268 }),
3269 ),
3270 ),
3271 ),
3272 resumeThread: Effect.fn("CursorAdapterV2.resumeThread")(
3273 function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) {
3274 const agentId = nativeThreadId(threadInput.providerThread);
3275 const opened = yield* openAgent({
3276 operation: "resume",
3277 agentId,
3278 storeCwd: threadInput.providerThread.nativeMetadata?.cursorStoreCwd,
3279 threadId: threadInput.providerThread.appThreadId ?? input.threadId,
3280 modelSelection: input.modelSelection,
3281 runtimePolicy: input.runtimePolicy,
3282 });
3283 const now = yield* DateTime.now;
3284 return {
3285 ...threadInput.providerThread,
3286 nativeMetadata: {
3287 ...threadInput.providerThread.nativeMetadata,
3288 cursorStoreCwd: opened.storeCwd,
3289 },
3290 providerSessionId: input.providerSessionId,
3291 status: "idle" as const,
3292 updatedAt: now,
3293 };
3294 },
3295 (effect, threadInput) =>
3296 effect.pipe(
3297 Effect.mapError(
3298 (cause) =>
3299 new ProviderAdapter.ProviderAdapterResumeThreadError({
3300 driver: CursorAgentSdk.CURSOR_PROVIDER,
3301 providerSessionId: input.providerSessionId,
3302 providerThreadId: threadInput.providerThread.id,
3303 cause,
3304 }),
3305 ),
3306 ),
3307 ),
3308 startTurn,
3309 resumeTurn: (input) => startTurn(ProviderAdapter.resumeTurnInput(input)),
3310 compactThread: (turnInput) =>
3311 startTurn({
3312 ...turnInput,
3313 message: { ...turnInput.message, text: "/compress" },
3314 }),
3315 steerTurn: Effect.fn("CursorAdapterV2.steerTurn")(
3316 function* (turnInput: ProviderAdapter.ProviderAdapterV2SteerInput) {
3317 const context = yield* Ref.get(activeTurn);
3318 if (
3319 context === null ||
3320 context.finalized ||
3321 context.providerTurnId !== turnInput.providerTurnId
3322 ) {
3323 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3324 driver: CursorAgentSdk.CURSOR_PROVIDER,
3325 detail: `Cursor provider turn ${turnInput.providerTurnId} is not active.`,
3326 });
3327 }
3328 // The live run already has the runtime instructions from startTurn.
3329 const text = yield* providerMessageTextWithAttachmentPaths({
3330 text: yield* resolveCursorSkillText(
3331 turnInput.message.text,
3332 context.input.runtimePolicy.cwd ?? undefined,
3333 ),
3334 attachments: turnInput.message.attachments,
3335 resolveAttachmentPath: host.resolveAttachmentPath,
3336 resolveExtractedTextPath: host.resolveExtractedTextPath,
3337 });
3338 if (text.trim().length === 0) {
3339 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3340 driver: CursorAgentSdk.CURSOR_PROVIDER,
3341 detail: "Cursor steer requires non-empty text.",
3342 });
3343 }
3344 const outcome =
3345 context.run.steer === undefined
3346 ? "revert_to_followup"
3347 : yield* context.run.steer(text);
3348 if (outcome === "complete_delivered") {
3349 return;
3350 }
3351 if (context.interrupted) {
3352 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3353 driver: CursorAgentSdk.CURSOR_PROVIDER,
3354 detail: "Cursor steer was interrupted before the run could take it.",
3355 });
3356 }
3357 return yield* new ProviderAdapter.ProviderAdapterSteerDeclinedError({
3358 driver: CursorAgentSdk.CURSOR_PROVIDER,
3359 providerThreadId: turnInput.providerThread.id,
3360 providerTurnId: turnInput.providerTurnId,
3361 });
3362 },
3363 (effect, turnInput) =>
3364 effect.pipe(
3365 Effect.mapError((cause) =>
3366 cause._tag === "ProviderAdapterSteerDeclinedError"
3367 ? cause
3368 : new ProviderAdapter.ProviderAdapterSteerRunError({
3369 driver: CursorAgentSdk.CURSOR_PROVIDER,
3370 providerThreadId: turnInput.providerThread.id,
3371 providerTurnId: turnInput.providerTurnId,
3372 cause,
3373 }),
3374 ),
3375 ),
3376 ),
3377 awaitBackgroundTasks: Effect.fn("CursorAdapterV2.awaitBackgroundTasks")(function* ({
3378 providerThread,
3379 taskIds,
3380 awaited,
3381 }) {
3382 // Cursor shows the agent a shell's id and its pid; either names it.
3383 const matched = [...new Set(taskIds)].filter((taskId) => {
3384 const shell =
3385 backgroundShells.get(taskId) ??
3386 [...backgroundShells.values()].find(
3387 (shell) => shell.pid !== undefined && String(shell.pid) === taskId,
3388 );
3389 if (shell?.providerThreadId !== providerThread.id) return false;
3390 shell.awaited = awaited;
3391 return true;
3392 });
3393 if (matched.length > 0) yield* publishBackgroundShells(providerThread.id);
3394 return { matched };
3395 }),
3396 stopTask: ({ providerThread, taskId }) =>
3397 Effect.sync(() => {
3398 const shell = backgroundShells.get(taskId);
3399 if (shell?.providerThreadId === providerThread.id) shell.stop();
3400 }),
3401 interruptTurn: Effect.fn("CursorAdapterV2.interruptTurn")(
3402 function* (turnInput: ProviderAdapter.ProviderAdapterV2InterruptInput) {
3403 const context = yield* Ref.get(activeTurn);
3404 // A user Stop ends what the agent left running too; a steer leaves it alone.
3405 if (turnInput.requestRuntimeRestart === true) {
3406 if (latestRunId !== undefined) stoppedRuns.add(latestRunId);
3407 yield* stopBackgroundShells(turnInput.providerThread.id);
3408 }
3409 if (context === null && turnInput.requestRuntimeRestart === true) return;
3410 if (context?.providerTurnId !== turnInput.providerTurnId) {
3411 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3412 driver: CursorAgentSdk.CURSOR_PROVIDER,
3413 detail: `Cursor provider turn ${turnInput.providerTurnId} is not active.`,
3414 });
3415 }
3416 context.interrupted = true;
3417 yield* context.run.cancel;
3418 const stopped = yield* Deferred.await(context.completed).pipe(
3419 Effect.timeoutOption("10 seconds"),
3420 );
3421 if (Option.isSome(stopped)) {
3422 return;
3423 }
3424 yield* Effect.logWarning("orchestration-v2.cursor-interrupt-timeout", {
3425 providerSessionId: input.providerSessionId,
3426 providerThreadId: turnInput.providerThread.id,
3427 providerTurnId: turnInput.providerTurnId,
3428 });
3429 yield* finalizeTurn({ context, status: "interrupted" });
3430 },
3431 (effect, turnInput) =>
3432 effect.pipe(
3433 Effect.mapError(
3434 (cause) =>
3435 new ProviderAdapter.ProviderAdapterInterruptError({
3436 driver: CursorAgentSdk.CURSOR_PROVIDER,
3437 providerThreadId: turnInput.providerThread.id,
3438 providerTurnId: turnInput.providerTurnId,
3439 cause,
3440 }),
3441 ),
3442 ),
3443 ),
3444 respondToRuntimeRequest: (requestInput) =>
3445 Effect.fail(
3446 new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
3447 driver: CursorAgentSdk.CURSOR_PROVIDER,
3448 requestId: requestInput.requestId,
3449 cause: new ProviderAdapter.ProviderAdapterProtocolError({
3450 driver: CursorAgentSdk.CURSOR_PROVIDER,
3451 detail: "Cursor Agent SDK does not expose interactive approval requests.",
3452 }),
3453 }),
3454 ),
3455 readThreadSnapshot: Effect.fn("CursorAdapterV2.readThreadSnapshot")(
3456 function* (snapshotInput) {
3457 const requestedAgentId = nativeThreadId(snapshotInput.providerThread);
3458 const agent = yield* openAgent({
3459 operation: "resume",
3460 agentId: requestedAgentId,
3461 storeCwd: snapshotInput.providerThread.nativeMetadata?.cursorStoreCwd,
3462 threadId: snapshotInput.providerThread.appThreadId ?? input.threadId,
3463 modelSelection: input.modelSelection,
3464 runtimePolicy: input.runtimePolicy,
3465 });
3466 const messages = yield* agent.session.listMessages;
3467 const now = yield* DateTime.now;
3468 const threadId = snapshotInput.providerThread.appThreadId ?? input.threadId;
3469 const projectedMessages: Array<OrchestrationV2ConversationMessage> = messages.flatMap(
3470 (message) => {
3471 const text = textFromAgentMessage(message);
3472 if (text.length === 0) {
3473 return [];
3474 }
3475 return [
3476 {
3477 createdBy: message.type === "user" ? "user" : "agent",
3478 creationSource: "provider",
3479 id: idAllocator.derive.messageFromProviderItem({
3480 driver: CursorAgentSdk.CURSOR_PROVIDER,
3481 nativeItemId: message.uuid,
3482 }),
3483 threadId,
3484 runId: null,
3485 nodeId: null,
3486 role: message.type,
3487 text,
3488 attachments: [],
3489 streaming: false,
3490 createdAt: now,
3491 updatedAt: now,
3492 },
3493 ];
3494 },
3495 );
3496 return {
3497 providerThread: {
3498 ...snapshotInput.providerThread,
3499 providerSessionId: input.providerSessionId,
3500 status: "idle" as const,
3501 updatedAt: now,
3502 },
3503 providerTurns: [],
3504 messages: projectedMessages,
3505 runtimeRequests: [],
3506 providerPayload: {
3507 agentId: requestedAgentId,
3508 messages,
3509 },
3510 };
3511 },
3512 (effect, snapshotInput) =>
3513 effect.pipe(
3514 Effect.mapError(
3515 (cause) =>
3516 new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
3517 driver: CursorAgentSdk.CURSOR_PROVIDER,
3518 providerThreadId: snapshotInput.providerThread.id,
3519 cause,
3520 }),
3521 ),
3522 ),
3523 ),
3524 rollbackThread: Effect.fn("CursorAdapterV2.rollbackThread")(
3525 function* (rollbackInput: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) {
3526 const current = yield* Ref.get(activeTurn);
3527 if (current !== null) {
3528 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3529 driver: CursorAgentSdk.CURSOR_PROVIDER,
3530 detail: `Cannot roll back Cursor provider thread ${rollbackInput.providerThread.id} while turn ${current.providerTurnId} is active.`,
3531 });
3532 }
3533 const threadId = rollbackInput.providerThread.appThreadId ?? input.threadId;
3534 const { target } = rollbackInput;
3535 // The kept turns may predate a compaction, so the instructions are sent again.
3536 const forgetConversation = (agent: string) =>
3537 Effect.all([
3538 Ref.set(told, {
3539 agent,
3540 orchestration: false,
3541 device: false,
3542 backgroundWait: false,
3543 runtime: undefined,
3544 }),
3545 Ref.set(interruptedPrompt, null),
3546 Ref.set(resumedAgent, null),
3547 // A shell the discarded runs left running must not wake the rewound thread.
3548 stopBackgroundShells(rollbackInput.providerThread.id),
3549 ]);
3550 const now = yield* DateTime.now;
3551 if (target.type === "provider_turn") {
3552 const keptRunId = target.providerTurn.nativeTurnRef?.nativeId;
3553 if (keptRunId == null) {
3554 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3555 driver: CursorAgentSdk.CURSOR_PROVIDER,
3556 detail: `Provider turn ${target.providerTurn.id} has no Cursor run id.`,
3557 });
3558 }
3559 const agent = yield* openAgent({
3560 operation: "resume",
3561 agentId: nativeThreadId(rollbackInput.providerThread),
3562 storeCwd: rollbackInput.providerThread.nativeMetadata?.cursorStoreCwd,
3563 threadId,
3564 modelSelection: input.modelSelection,
3565 runtimePolicy: input.runtimePolicy,
3566 });
3567 if (agent.session.rewindAfterRun === undefined) {
3568 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3569 driver: CursorAgentSdk.CURSOR_PROVIDER,
3570 detail: "This Cursor SDK session cannot rewind its conversation.",
3571 });
3572 }
3573 yield* agent.session.rewindAfterRun(keptRunId);
3574 yield* forgetConversation(agent.nativeThreadId);
3575 yield* agent.session.close.pipe(Effect.ignore);
3576 yield* Ref.set(liveAgent, null);
3577 return {
3578 providerThread: {
3579 ...rollbackInput.providerThread,
3580 providerSessionId: input.providerSessionId,
3581 status: "idle" as const,
3582 updatedAt: now,
3583 },
3584 providerTurns: [],
3585 messages: [],
3586 runtimeRequests: [],
3587 };
3588 }
3589 // The first run starts without a checkpoint, so there is nothing to rewind onto.
3590 const opened = yield* openAgent({
3591 operation: "create",
3592 threadId,
3593 modelSelection: input.modelSelection,
3594 runtimePolicy: input.runtimePolicy,
3595 });
3596 yield* forgetConversation(opened.nativeThreadId);
3597 return {
3598 providerThread: {
3599 ...rollbackInput.providerThread,
3600 providerSessionId: input.providerSessionId,
3601 nativeThreadRef: {
3602 driver: CursorAgentSdk.CURSOR_PROVIDER,
3603 nativeId: opened.nativeThreadId,
3604 strength: "strong" as const,
3605 },
3606 nativeConversationHeadRef: null,
3607 nativeMetadata: {
3608 ...rollbackInput.providerThread.nativeMetadata,
3609 cursorStoreCwd: opened.storeCwd,
3610 },
3611 status: "idle" as const,
3612 updatedAt: now,
3613 },
3614 providerTurns: [],
3615 messages: [],
3616 runtimeRequests: [],
3617 };
3618 },
3619 (effect, rollbackInput) =>
3620 effect.pipe(
3621 Effect.mapError(
3622 (cause) =>
3623 new ProviderAdapter.ProviderAdapterRollbackThreadError({
3624 driver: CursorAgentSdk.CURSOR_PROVIDER,
3625 providerThreadId: rollbackInput.providerThread.id,
3626 checkpointId: rollbackInput.target.checkpointId,
3627 cause,
3628 }),
3629 ),
3630 ),
3631 ),
3632 forkThread: (forkInput) =>
3633 Effect.fail(
3634 new ProviderAdapter.ProviderAdapterForkThreadError({
3635 driver: CursorAgentSdk.CURSOR_PROVIDER,
3636 providerThreadId: forkInput.sourceProviderThread.id,
3637 cause: "Cursor Agent SDK does not expose native agent forks.",
3638 }),
3639 ),
3640 };
3641 return runtime;
3642 },
3643 (effect, input) =>
3644 effect.pipe(
3645 Effect.mapError(
3646 (cause) =>
3647 new ProviderAdapter.ProviderAdapterOpenSessionError({
3648 driver: CursorAgentSdk.CURSOR_PROVIDER,
3649 providerSessionId: input.providerSessionId,
3650 cause,
3651 }),
3652 ),
3653 ),
3654 ),
3655 });
3656 });
3657
3658 export type CursorAdapterV2DriverEnv =
3659 | CursorAgentSdk.CursorAgentSdkRunner
3660 | ChildProcessSpawner.ChildProcessSpawner
3661 | FileSystem.FileSystem
3662 | Path.Path
3663 | IdAllocator.IdAllocatorV2
3664 | McpProviderSessions.McpProviderSessions
3665 | ProviderHost.ProviderHost;