Tools and features

Requests, reasoning and sessions

Full reference

30 reviewed records from the Agent CLI and the desktop app: the AgentService request and response messages, where requests go, the reasoning events streamed back, and how sessions are stored. Each entry gives the exact shipped bytes and their location; schemas are decoded or reconstructed into tables above the bytes they come from.

Request and response schemas

Agent client stream message schema

Source: index.js (Agent CLI) · bytes 5731084–5731360 · SHA-256 8d31f8043981…

Decoded from the shipped protobuf descriptor for AgentClientMessage; referenced types resolved through Cursor's own generated classes (agent.v1).

No. Field Type Label
1 run_request AgentRunRequest oneof message
2 exec_client_message ExecClientMessage oneof message
5 exec_client_control_message ExecClientControlMessage oneof message
3 kv_client_message KvClientMessage oneof message
4 conversation_action ConversationAction oneof message
6 interaction_response InteractionResponse oneof message
7 client_heartbeat ClientHeartbeat oneof message
8 prewarm_request PrewarmRequest oneof message
Exact shipped text
AgentClientMessage|1 run_request #0 message|2 exec_client_message #1 message|5 exec_client_control_message #2 message|3 kv_client_message #3 message|4 conversation_action #4 message|6 interaction_response #5 message|7 client_heartbeat #6 message|8 prewarm_request #7 message

Agent run request schema

Source: index.js (Agent CLI) · bytes 5709483–5710435 · SHA-256 a29a9ef4824c…

Decoded from the shipped protobuf descriptor for AgentRunRequest; referenced types resolved through Cursor's own generated classes (agent.v1).

No. Field Type Label
1 conversation_state ConversationStateStructure —
2 action ConversationAction —
3 model_details ModelDetails —
9 requested_model RequestedModel optional
4 mcp_tools McpTools —
5 conversation_id string optional
6 mcp_file_system_options McpFileSystemOptions optional
7 skill_options SkillOptions optional
8 custom_system_prompt string optional
10 suggest_next_prompt bool optional
11 subagent_type_name string optional
12 exclude_workspace_context bool optional
13 harness string optional
14 selected_subagent_models RequestedModel repeated
15 selected_subagent_model_details ModelDetails repeated
16 conversation_group_id string optional
17 pre_fetched_blobs PreFetchedBlob repeated
18 dev_raw_model_slug string optional
19 client_supports_inline_images bool optional
20 subagent_model_overrides SubagentModelOverride repeated
21 can_create_cloud_subagents bool optional
22 suppress_subagent_progress_update_tool bool optional
23 client_supports_send_to_user bool optional
24 computer_use_coordinate_mode string optional
25 run_id string optional
26 agent_session_id string optional
27 client_supports_prompt_context_usage_rpc bool optional
28 client_supports_routed_model_update bool optional
29 system_prompt_spec SystemPromptSpec optional
30 client_llm_gateway_credential ClientLlmGatewayCredential optional
31 client_supports_preview_card bool optional
32 started_as_new_project bool optional
33 first_project_onboarding bool optional
Exact shipped text
AgentRunRequest|1 conversation_state #0|2 action #1|3 model_details #2|9 requested_model #3?|4 mcp_tools #4|5 conversation_id 9?|6 mcp_file_system_options #5?|7 skill_options #6?|8 custom_system_prompt 9?|10 suggest_next_prompt 8?|11 subagent_type_name 9?|12 exclude_workspace_context 8?|13 harness 9?|14 selected_subagent_models #3*|15 selected_subagent_model_details #2*|16 conversation_group_id 9?|17 pre_fetched_blobs #7*|18 dev_raw_model_slug 9?|19 client_supports_inline_images 8?|20 subagent_model_overrides #8*|21 can_create_cloud_subagents 8?|22 suppress_subagent_progress_update_tool 8?|23 client_supports_send_to_user 8?|24 computer_use_coordinate_mode 9?|25 run_id 9?|26 agent_session_id 9?|27 client_supports_prompt_context_usage_rpc 8?|28 client_supports_routed_model_update 8?|29 system_prompt_spec #9?|30 client_llm_gateway_credential #10?|31 client_supports_preview_card 8?|32 started_as_new_project 8?|33 first_project_onboarding 8?

Agent server stream message schema

Source: index.js (Agent CLI) · bytes 5732279–5732531 · SHA-256 ebec865243ff…

Decoded from the shipped protobuf descriptor for AgentServerMessage; referenced types resolved through Cursor's own generated classes (agent.v1).

No. Field Type Label
1 interaction_update InteractionUpdate oneof message
2 exec_server_message ExecServerMessage oneof message
5 exec_server_control_message ExecServerControlMessage oneof message
3 conversation_checkpoint_update ConversationStateStructure oneof message
4 kv_server_message KvServerMessage oneof message
7 interaction_query InteractionQuery oneof message
8 ttft_breakdown TtftBreakdown —
Exact shipped text
AgentServerMessage|1 interaction_update #0 message|2 exec_server_message #1 message|5 exec_server_control_message #2 message|3 conversation_checkpoint_update #3 message|4 kv_server_message #4 message|7 interaction_query #5 message|8 ttft_breakdown #6

Daemon response mapping

Source: extensions/cursor-agent-host/dist/agent-host-daemon/dist/bin/daemon.cjs (desktop) · bytes 26209529–26224784 · SHA-256 63de50c8a34e…

Unminified desktop source for src/map-response.ts (15,255 characters), the code behind the daemon response mapping. It reads as shipped, below.

Exact shipped text
// src/map-response.ts
function toCreateSessionResponse() {
  return new CreateAgentHostSessionResponse();
}
function toForkSessionResponse(res) {
  return new ForkAgentHostSessionResponse({ sessionId: res.sessionId });
}
function toListSessionsResponse(res) {
  return new ListAgentHostSessionsResponse({
    sessions: res.sessions.map(toProtoSession)
  });
}
function toListWorkspacesResponse(res) {
  return new ListAgentHostWorkspacesResponse({
    workspaces: res.workspaces.map(toProtoWorkspace)
  });
}
function toProtoWorkspace(workspace) {
  return new AgentHostWorkspace({
    workspacePaths: [...workspace.workspacePaths],
    ...workspace.worktreeMainPath === void 0 ? {} : { worktreeMainPath: workspace.worktreeMainPath },
    ...workspace.displayPath === void 0 ? {} : { displayPath: workspace.displayPath }
  });
}
function toSendMessageResponse(res) {
  return new SendAgentHostMessageResponse({
    turnId: res.turnId,
    deliveredAs: res.deliveredAs
  });
}
function toSendActionResponse(res) {
  return new SendAgentHostActionResponse({
    turnId: res.turnId,
    deliveredAs: res.deliveredAs
  });
}
function toDeleteSessionResponse() {
  return new DeleteAgentHostSessionResponse();
}
function toInterruptTurnResponse(res) {
  return new InterruptAgentHostTurnResponse({ interrupted: res.interrupted });
}
function toCancelQueuedTurnResponse(res) {
  return new CancelQueuedAgentHostTurnResponse({ cancelled: res.cancelled });
}
function toRespondToInteractionResponse(res) {
  return new RespondToAgentHostInteractionResponse({ status: res.status });
}
function toAbortBackgroundWorkResponse(res) {
  return new AbortAgentHostBackgroundWorkResponse({ aborted: res.aborted });
}
function toAbortAllBackgroundWorkResponse(res) {
  return new AbortAllAgentHostBackgroundWorkResponse({
    abortedCount: res.abortedCount
  });
}
function toWatchSessionsEvent(event) {
  switch (event.event.case) {
    case "snapshot":
      return new WatchAgentHostSessionsEvent({
        event: {
          case: "snapshot",
          value: new AgentHostSessionsSnapshot({
            sessions: event.event.value.sessions.map(toProtoSession)
          })
        }
      });
    case "added":
      return new WatchAgentHostSessionsEvent({
        event: {
          case: "added",
          value: new AgentHostSessionAdded({
            session: toProtoSession(event.event.value.session)
          })
        }
      });
    case "updated":
      return new WatchAgentHostSessionsEvent({
        event: {
          case: "updated",
          value: new AgentHostSessionUpdated({
            session: toProtoSession(event.event.value.session)
          })
        }
      });
    case "deleted":
      return new WatchAgentHostSessionsEvent({
        event: {
          case: "deleted",
          value: new AgentHostSessionDeleted({
            sessionId: event.event.value.sessionId
          })
        }
      });
  }
}
function toWatchInteractionsEvent(event) {
  const interactions = event.event.value.interactions.map(
    (interaction) => new AgentHostPendingInteraction(interaction)
  );
  if (event.event.case === "snapshot") {
    return new WatchAgentHostSessionInteractionsEvent({
      event: {
        case: "snapshot",
        value: new AgentHostSessionInteractionsSnapshot({ interactions })
      }
    });
  }
  return new WatchAgentHostSessionInteractionsEvent({
    event: {
      case: "state",
      value: new AgentHostSessionInteractionsState({ interactions })
    }
  });
}
function toWatchBackgroundWorkEvent(event) {
  const work = event.event.value.work.map(toProtoBackgroundWork);
  if (event.event.case === "snapshot") {
    return new WatchAgentHostSessionBackgroundWorkEvent({
      event: {
        case: "snapshot",
        value: new AgentHostSessionBackgroundWorkSnapshot({ work })
      }
    });
  }
  return new WatchAgentHostSessionBackgroundWorkEvent({
    event: {
      case: "state",
      value: new AgentHostSessionBackgroundWorkState({ work })
    }
  });
}
function toWatchTurnLifecycleEvent(event) {
  return new WatchAgentHostSessionTurnLifecycleEvent({ event: event.event });
}
function toSessionEvent(event) {
  return new AgentHostSessionEvent({
    eventId: event.eventId,
    event: toSessionEventPayload(event)
  });
}
function toSessionEventPayload(event) {
  switch (event.event.case) {
    case "interactionUpdate":
      return { case: "interactionUpdate", value: event.event.value };
    case "conversationState":
      return { case: "conversationState", value: event.event.value };
    case "turnStarted":
      return {
        case: "turnStarted",
        value: new AgentHostTurnStarted(event.event.value)
      };
    case "turnAwaitingInput":
      return {
        case: "turnAwaitingInput",
        value: new AgentHostTurnAwaitingInput(event.event.value)
      };
    case "turnSettled":
      return {
        case: "turnSettled",
        value: toTurnSettled(event.event.value)
      };
    case "interactionResolved":
      return {
        case: "interactionResolved",
        value: toInteractionResolved(event.event.value)
      };
    case "subagentStarted":
      return {
        case: "subagentStarted",
        value: new AgentHostSubagentStarted(event.event.value)
      };
    case "backgroundTaskCompleted":
      return {
        case: "backgroundTaskCompleted",
        value: new AgentHostBackgroundTaskCompleted({
          completion: event.event.value.completion
        })
      };
    case "turnInteractionsSuperseded":
      return {
        case: "turnInteractionsSuperseded",
        value: new AgentHostTurnInteractionsSuperseded(event.event.value)
      };
  }
}
function toTurnSettled(value) {
  return new AgentHostTurnSettled({
    turnId: value.turnId,
    outcome: value.outcome,
    detail: value.detail,
    interruptedBy: value.interruptedBy,
    error: value.error === void 0 ? void 0 : new AgentHostTurnError(value.error)
  });
}
function toInteractionResolved(value) {
  switch (value.resolution.case) {
    case "responded":
      return new AgentHostInteractionResolved({
        turnId: value.turnId,
        interactionId: value.interactionId,
        resolution: { case: "responded", value: value.resolution.value }
      });
    case "cancelled":
      return new AgentHostInteractionResolved({
        turnId: value.turnId,
        interactionId: value.interactionId,
        resolution: {
          case: "cancelled",
          value: new AgentHostInteractionCancelled(value.resolution.value)
        }
      });
    case "failed":
      return new AgentHostInteractionResolved({
        turnId: value.turnId,
        interactionId: value.interactionId,
        resolution: {
          case: "failed",
          value: new AgentHostInteractionFailed(value.resolution.value)
        }
      });
    case void 0:
      return new AgentHostInteractionResolved({
        turnId: value.turnId,
        interactionId: value.interactionId,
        resolution: { case: void 0 }
      });
  }
}
function toProtoSession(session) {
  return new AgentHostSession({
    sessionId: session.sessionId,
    status: session.status,
    lastEventId: session.lastEventId,
    forkedFromSessionId: session.forkedFromSessionId,
    title: session.title,
    parent: session.parent === void 0 ? void 0 : new SessionParent(session.parent),
    updatedAt: session.updatedAt,
    modelId: session.modelId,
    runningTurnId: session.runningTurnId,
    queuedTurnIds: session.queuedTurnIds,
    workspace: session.workspace === void 0 ? void 0 : toProtoWorkspace(session.workspace)
  });
}
function toSurfaceChannelEvent(event) {
  if (event.case === "heartbeat") {
    return new AgentHostSurfaceChannelEvent({
      event: {
        case: "heartbeat",
        value: new AgentHostSurfaceChannelHeartbeat({
          epochMs: event.heartbeat.epochMs
        })
      }
    });
  }
  if (event.case === "auth_refresh") {
    return new AgentHostSurfaceChannelEvent({
      event: {
        case: "authRefresh",
        value: new AgentHostSurfaceAuthRefreshRequest({
          reason: event.authRefresh.reason
        })
      }
    });
  }
  return new AgentHostSurfaceChannelEvent({
    event: {
      case: "invocation",
      value: new AgentHostSurfaceCallbackInvocation({
        callbackId: event.invocation.callbackId,
        sessionId: event.invocation.sessionId,
        ...event.invocation.rootSessionId === void 0 || event.invocation.rootSessionId.length === 0 ? {} : { rootSessionId: event.invocation.rootSessionId },
        targetClientInstanceId: event.invocation.targetClientInstanceId,
        kind: toSurfaceInvocationKind(event.invocation)
      })
    }
  });
}
function toSurfaceInvocationKind(invocation) {
  switch (invocation.kind) {
    case "approval":
      return {
        case: "approval",
        value: invocation.approval ?? new AgentHostSurfaceApprovalRequest()
      };
    case "mcp_elicitation":
      return {
        case: "mcpElicitation",
        value: invocation.mcpElicitation ?? new AgentHostSurfaceMcpElicitationRequest()
      };
    case "permissions_pull":
      return {
        case: "permissionsPull",
        value: new AgentHostSurfacePermissionsPullRequest()
      };
    case "conversation_search":
      return {
        case: "conversationSearch",
        value: invocation.conversationSearch ?? new AgentHostSurfaceConversationSearchRequest()
      };
    case "file_change_notify":
      return {
        case: "fileChangeNotify",
        value: invocation.fileChangeNotify ?? new AgentHostSurfaceFileChangeNotify()
      };
    case "hook":
      return {
        case: "hook",
        value: invocation.hook ?? new AgentHostSurfaceHookRequest()
      };
    case "git":
      return {
        case: "git",
        value: invocation.git ?? new AgentHostSurfaceGitRequest()
      };
    case "canvas":
      return {
        case: "canvas",
        value: invocation.canvas ?? new AgentHostSurfaceCanvasRequest()
      };
    case "agent_host_plugins":
      return {
        case: "agentHostPlugins",
        value: invocation.agentHostPlugins ?? new AgentHostSurfacePluginsRequest()
      };
    case "agent_host_agent_store":
      return {
        case: "agentHostAgentStore",
        value: invocation.agentHostAgentStore ?? new AgentHostSurfaceAgentStoreRequest()
      };
    case "mcp_writer":
      return {
        case: "mcpWriter",
        value: invocation.mcpWriter ?? new AgentHostSurfaceMcpWriterRequest()
      };
    case "cloud_subagent":
      return {
        case: "cloudSubagent",
        value: invocation.cloudSubagent ?? new AgentHostSurfaceCloudSubagentRequest()
      };
    case "adopt":
      return {
        case: "adopt",
        value: invocation.adopt ?? new AgentHostSurfaceAdoptRequest()
      };
    case "saved_model_parameters":
      return {
        case: "savedModelParameters",
        value: invocation.savedModelParameters ?? new AgentHostSurfaceSavedModelParametersRequest()
      };
    case "required_global_commands":
      return {
        case: "requiredGlobalCommands",
        value: invocation.requiredGlobalCommands ?? new AgentHostSurfaceRequiredGlobalCommandsRequest()
      };
    case "find_subagent":
      return {
        case: "findSubagent",
        value: new AgentHostSurfaceFindSubagentRequest()
      };
    case "request_context":
      return {
        case: "requestContext",
        value: invocation.requestContext ?? new AgentHostSurfaceRequestContextRequest()
      };
    default: {
      const exhaustive = invocation.kind;
      return exhaustive;
    }
  }
}
function toReadFileResponse(response) {
  const fields = {
    totalBytes: response.totalBytes,
    mtimeMs: response.mtimeMs
  };
  switch (response.result.case) {
    case "chunk": {
      const chunk = response.result.value;
      return new ReadAgentHostFileResponse({
        ...fields,
        result: {
          case: "chunk",
          value: new AgentHostFileChunk({ offset: chunk.offset, data: chunk.data })
        }
      });
    }
    case "notModified":
      return new ReadAgentHostFileResponse({
        ...fields,
        result: {
          case: "notModified",
          value: new AgentHostFileNotModified()
        }
      });
    case "tooLarge":
      return new ReadAgentHostFileResponse({
        ...fields,
        result: {
          case: "tooLarge",
          value: new AgentHostFileTooLarge({
            maxBytes: response.result.value.maxBytes
          })
        }
      });
  }
}
function toWatchShellOutputEvent(event) {
  if (event.type === "snapshot") {
    return new WatchAgentHostSessionShellOutputEvent({
      event: {
        case: "snapshot",
        value: new AgentHostShellOutputSnapshot({
          shellId: event.snapshot.shellId,
          command: event.snapshot.command,
          cwd: event.snapshot.cwd,
          state: toProtoShellLifecycleState(event.snapshot.state),
          bufferedOutput: new Uint8Array(event.snapshot.bufferedOutput),
          nextOutputOffset: event.snapshot.nextOutputOffset,
          adopted: event.snapshot.adopted,
          ...event.snapshot.toolCallId === void 0 ? {} : { toolCallId: event.snapshot.toolCallId },
          ...event.snapshot.title === void 0 ? {} : { title: event.snapshot.title }
        })
      }
    });
  }
  if (event.type === "chunk") {
    return new WatchAgentHostSessionShellOutputEvent({
      event: {
        case: "output",
        value: new AgentHostShellOutputChunk({
          shellId: event.chunk.shellId,
          outputOffset: event.chunk.outputOffset,
          isBackpressured: event.chunk.isBackpressured,
          stream: event.chunk.stream === "stdout" ? { case: "stdout", value: new Uint8Array(event.chunk.data) } : { case: "stderr", value: new Uint8Array(event.chunk.data) }
        })
      }
    });
  }
  return new WatchAgentHostSessionShellOutputEvent({
    event: {
      case: "lifecycle",
      value: new AgentHostShellLifecycle({
        shellId: event.lifecycle.shellId,
        state: toProtoShellLifecycleState(event.lifecycle.state),
        ...event.lifecycle.exitCode === void 0 ? {} : { exitCode: event.lifecycle.exitCode },
        ...event.lifecycle.abortReason === void 0 ? {} : { abortReason: event.lifecycle.abortReason }
      })
    }
  });
}
function toWriteShellInputResponse(result) {
  return new WriteAgentHostSessionShellInputResponse({
    bytesAccepted: result.bytesAccepted
  });
}
function toProtoShellLifecycleState(state) {
  switch (state) {
    case "starting":
      return AgentHostShellLifecycleState.STARTING;
    case "running":
      return AgentHostShellLifecycleState.RUNNING;
    case "exited":
      return AgentHostShellLifecycleState.EXITED;
    case "aborted":
      return AgentHostShellLifecycleState.ABORTED;
    default:
      return AgentHostShellLifecycleState.UNSPECIFIED;
  }
}
function toProtoBackgroundWork(work) {
  return new AgentHostBackgroundWork({
    id: work.id,
    kind: work.kind,
    state: work.state,
    ownerId: work.ownerId,
    hasAbort: work.hasAbort,
    metadata: work.metadata
  });
}
var init_map_response = __esm({
  "src/map-response.ts"() {
    "use strict";
    init_agent_host_pb();
    init_agent_host_surface_pb();
  }
});

System prompt replacement and append schema (desktop)

Source: extensions/cursor-agent-exec/dist/main.js (desktop) · bytes 2347701–2347752 · SHA-256 9d6090e2283e…

Decoded from the shipped protobuf descriptor for SystemPromptSpec.

No. Field Type Label
1 replace string oneof spec
2 append string oneof spec
Exact shipped text
SystemPromptSpec|1 replace 9 spec|2 append 9 spec

System prompt replacement and append schema (Agent CLI)

Source: index.js (Agent CLI) · bytes 6013651–6013702 · SHA-256 9d6090e2283e…

Decoded from the shipped protobuf descriptor for SystemPromptSpec.

No. Field Type Label
1 replace string oneof spec
2 append string oneof spec
Exact shipped text
SystemPromptSpec|1 replace 9 spec|2 append 9 spec

Endpoints and request routing

Agent service client and routing

Source: index.js (Agent CLI) · bytes 2210630–2234470 · SHA-256 0c23f808751d…

Minified Agent CLI webpack module ./src/client.ts (20,305 characters), the code behind the agent service client and routing. Identifiers are minified; the exact shipped code is below.

Exact shipped text
"./src/client.ts"(t,e,r){"use strict";r.d(e,{hO:()=>Z,uU:()=>V,t9:()=>nt,OC:()=>rt,Mr:()=>tt,OU:()=>st,BK:()=>Y,Np:()=>it,ms:()=>W,Bu:()=>et});var n=r("../agent-client/dist/index.js"),s=r("node:crypto"),i=r("../proto/dist/generated/aiserver/v1/bidi_pb.js"),a=r("../../../../../../../../../../<build path>"),o=r("../../../../../../../../../../<build path>"),c=r("../../../../../../../../../../<build path>"),u=r("../../../../../../../../../../<build path>");function l(t){return t instanceof Error?t:new Error(String(t))}class d extends Error{constructor(){super("Append failed"),this.name="AppendFailedError"}}class m{constructor(t,e,r,n,s={}){this.mapper=t,this.bidiClient=e,this.innerTransport=r,this.onError=n,this.binaryEncoding=!0===s.binaryEncoding,this.appendTimeoutMs=s.appendTimeoutMs??6e4}unary(t,e,r,n,s,i,a){return this.innerTransport.unary(t,e,r,n,s,i,a)}async stream(t,e,r,n,o,c,l){if(e.kind!==a.I.BiDiStreaming)return this.innerTransport.stream(t,e,r,n,o,c,l);const d=this.mapper.map(e),{requestId:m,header:p}=function(t){const e=t instanceof Headers?t.get("x-request-id"):Array.isArray(t)?t.find((([t])=>"x-request-id"===t))?.[1]:t?.["x-request-id"];if("string"==typeof e)return{requestId:e,header:t};const r=(0,s.randomUUID)();if(void 0===t){const t=new Headers;return t.set("x-request-id",r),{requestId:r,header:t}}return t instanceof Headers?t.set("x-request-id",r):Array.isArray(t)?t.push(["x-request-id",r]):"object"==typeof t&&null!==t&&(t["x-request-id"]=r),{requestId:r,header:t}}(o),f=new i.$r({requestId:m}),h=(0,u.T$)([f]);let g;const A=new Promise(((t,e)=>{g=e}));A.catch((()=>{}));const b=this.innerTransport.stream(t,d,r,n,p,h,l);this.startAppendingInputs(m,c,r,n,p,g);const y=await b,_=y.message,w={[Symbol.asyncIterator](){const t=_[Symbol.asyncIterator]();return{next:()=>Promise.race([t.next(),A]),return:e=>t.return?.(e)??Promise.resolve({done:!0,value:void 0}),throw:e=>t.throw?.(e)??Promise.resolve({done:!0,value:void 0})}}};return{...y,method:e,message:w}}startAppendingInputs(t,e,r,n,s,a){Promise.resolve().then((async()=>{let u=0;const m=[],p=e[Symbol.asyncIterator](),f=new AbortController,h=f.signal;let g,A;const b=new Promise(((t,e)=>{A=()=>e(new d)}));let y;if(b.catch((()=>{})),r?.aborted)f.abort(r.reason);else if(void 0!==r){const t=()=>{f.abort(r.reason),A()};r.addEventListener("abort",t,{once:!0}),g=()=>{r.removeEventListener("abort",t)}}try{for(;!h.aborted&&void 0===y;){const e=await Promise.race([p.next(),b]);if(e.done)break;const r=e.value,d=u++,g=new i.$r({requestId:t}),_=r.toBinary(),w=this.binaryEncoding?_.length:2*_.length,C=this.appendTimeoutMs+Math.ceil(w/131072*1e3),v=void 0!==n?Math.min(n,C):C,E=this.bidiClient.bidiAppend(this.binaryEncoding?{requestId:g,appendSeqno:BigInt(d),dataBinary:_}:{requestId:g,appendSeqno:BigInt(d),data:Buffer.from(_.buffer,_.byteOffset,_.byteLength).toString("hex")},{signal:h,timeoutMs:v,headers:s}).then((()=>{})).catch((t=>{var e;if(e=h,!0!==e?.aborted&&void 0===y){const e=t instanceof o.T&&t.code===c.C.DeadlineExceeded?new o.T(`bidi_append_deadline_exceeded: append seqno=${d} (${_.length} bytes) exceeded ${v}ms deadline`,c.C.DeadlineExceeded,void 0,void 0,t):l(t);y=e,f.abort(e),this.onError(e),a(e),A()}})).finally((()=>{const t=m.indexOf(E);t>-1&&m.splice(t,1)}));if(m.push(E),await Promise.resolve(),h.aborted||void 0!==y)break;m.length>=16&&await Promise.race(m)}await Promise.allSettled(m)}catch(t){if(await Promise.allSettled(m),t instanceof d)return;const e=l(t);f.abort(e),this.onError(e),a(e)}finally{g?.(),await(p.return?.())}}))}}var p=r("../context-rpc/dist/index.js"),f=r("../cursor-config/dist/request.js"),h=r("../proto/dist/generated/agent/v1/agent_service_pb.js");const g={typeName:"agent.v1.AgentService",methods:{run:{name:"Run",I:h.KS,O:h.Oy,kind:a.I.BiDiStreaming},runSSE:{name:"RunSSE",I:i.$r,O:h.Oy,kind:a.I.ServerStreaming},runPoll:{name:"RunPoll",I:i.hD,O:i.xy,kind:a.I.ServerStreaming},nameAgent:{name:"NameAgent",I:h.Il,O:h.mw,kind:a.I.Unary},updateConversationMetadata:{name:"UpdateConversationMetadata",I:h.vw,O:h.HJ,kind:a.I.Unary},createTranscriptOverview:{name:"CreateTranscriptOverview",I:h.BU,O:h.Hi,kind:a.I.Unary},getUsableModels:{name:"GetUsableModels",I:h.KD,O:h.sY,kind:a.I.Unary},getDefaultModelForCli:{name:"GetDefaultModelForCli",I:h.Tu,O:h.pe,kind:a.I.Unary},getAllowedModelIntents:{name:"GetAllowedModelIntents",I:h.Ov,O:h.k4,kind:a.I.Unary},uploadConversationBlobs:{name:"UploadConversationBlobs",I:h.yD,O:h.W$,kind:a.I.Unary},uploadLocalAgentRunToPromptQuality:{name:"UploadLocalAgentRunToPromptQuality",I:h.uK,O:h.eE,kind:a.I.Unary},getSignedUrlForAttachedMedia:{name:"GetSignedUrlForAttachedMedia",I:h.W3,O:h.wq,kind:a.I.Unary},notifyConversationClone:{name:"NotifyConversationClone",I:h.xk,O:h.JF,kind:a.I.Unary},getNewChatNudgeLegacyModelPicker:{name:"GetNewChatNudgeLegacyModelPicker",I:h.Pg,O:h.zP,kind:a.I.Unary},getNewChatNudgeParameterizedModelPicker:{name:"GetNewChatNudgeParameterizedModelPicker",I:h.hs,O:h.TW,kind:a.I.Unary},getPromptContextUsage:{name:"GetPromptContextUsage",I:h.Y3,O:h.KE,kind:a.I.Unary},listLocalSubscriptionTools:{name:"ListLocalSubscriptionTools",I:h.dw,O:h.JH,kind:a.I.Unary},callLocalSubscriptionTool:{name:"CallLocalSubscriptionTool",I:h.uw,O:h.uu,kind:a.I.Unary},streamLocalAgentMailbox:{name:"StreamLocalAgentMailbox",I:h.k5,O:h.ic,kind:a.I.ServerStreaming}}};var A=r("../proto/dist/generated/aiserver/v1/aiserver_connect.js"),b=r("../proto/dist/generated/aiserver/v1/analytics_pb.js");const y={typeName:"aiserver.v1.AnalyticsService",methods:{trackEvents:{name:"TrackEvents",I:b.cg,O:b.cS,kind:a.I.Unary},batch:{name:"Batch",I:b.qc,O:b.CY,kind:a.I.Unary},bootstrapStatsig:{name:"BootstrapStatsig",I:b.$F,O:b.lb,kind:a.I.Unary},getFirstWindowStatsigDecision:{name:"GetFirstWindowStatsigDecision",I:b.DF,O:b.dr,kind:a.I.Unary},submitLogs:{name:"SubmitLogs",I:b.ju,O:b.v5,kind:a.I.Unary},ingestConversation:{name:"IngestConversation",I:b.$g,O:b.xI,kind:a.I.Unary},uploadIssueTrace:{name:"UploadIssueTrace",I:b.TR,O:b.ri,kind:a.I.Unary},downloadIssueTraces:{name:"DownloadIssueTraces",I:b.ZJ,O:b.Fu,kind:a.I.Unary}}};var _=r("../proto/dist/generated/aiserver/v1/automations_pb.js");const w={typeName:"aiserver.v1.AutomationsService",methods:{createAutomation:{name:"CreateAutomation",I:_.HAU,O:_.P5X,kind:a.I.Unary},listAutomations:{name:"ListAutomations",I:_.mIE,O:_.as1,kind:a.I.Unary},getAutomation:{name:"GetAutomation",I:_.Vw6,O:_.xbi,kind:a.I.Unary},updateAutomation:{name:"UpdateAutomation",I:_.Gcl,O:_.q8Z,kind:a.I.Unary},createSandAutomation:{name:"CreateSandAutomation",I:_.HAU,O:_.P5X,kind:a.I.Unary},listSandAutomations:{name:"ListSandAutomations",I:_.sGK,O:_.as1,kind:a.I.Unary},getSandAutomation:{name:"GetSandAutomation",I:_.Vw6,O:_.xbi,kind:a.I.Unary},updateSandAutomation:{name:"UpdateSandAutomation",I:_.Gcl,O:_.q8Z,kind:a.I.Unary},deleteSandAutomation:{name:"DeleteSandAutomation",I:_.GPi,O:_.KPG,kind:a.I.Unary},reassignAutomationOwner:{name:"ReassignAutomationOwner",I:_.CPr,O:_.EaF,kind:a.I.Unary},updateAutomationAuthoringMode:{name:"UpdateAutomationAuthoringMode",I:_.UV_,O:_.cpm,kind:a.I.Unary},validateAutomationSpec:{name:"ValidateAutomationSpec",I:_.oZO,O:_.kpP,kind:a.I.Unary},applyAutomationSpec:{name:"ApplyAutomationSpec",I:_.Sob,O:_.i6X,kind:a.I.Unary},deleteAutomation:{name:"DeleteAutomation",I:_.GPi,O:_.KPG,kind:a.I.Unary},testAutomation:{name:"TestAutomation",I:_.rMM,O:_.znz,kind:a.I.Unary},testAutomationFilter:{name:"TestAutomationFilter",I:_.Dhf,O:_.jGS,kind:a.I.Unary},listAutomationRuns:{name:"ListAutomationRuns",I:_.NSb,O:_.n2U,kind:a.I.Unary},getAutomationRun:{name:"GetAutomationRun",I:_.cMg,O:_.Cvd,kind:a.I.Unary},listAllRuns:{name:"ListAllRuns",I:_.x1i,O:_.hG0,kind:a.I.Unary},listAgentSdkAutomationRuns:{name:"ListAgentSdkAutomationRuns",I:_.U50,O:_.OST,kind:a.I.Unary},getRunSummary:{name:"GetRunSummary",I:_.nn9,O:_.nSe,kind:a.I.Unary},getSecuritybotResolutionStats:{name:"GetSecuritybotResolutionStats",I:_.Gk8,O:_.UN0,kind:a.I.Unary},getApprovalAgentAnalytics:{name:"GetApprovalAgentAnalytics",I:_.KGK,O:_.O0E,kind:a.I.Unary},getManagedAutomationTeamSettings:{name:"GetManagedAutomationTeamSettings",I:_.yau,O:_.WAB,kind:a.I.Unary},updateManagedAutomationTeamSettings:{name:"UpdateManagedAutomationTeamSettings",I:_.xd7,O:_.poG,kind:a.I.Unary},getChangeMonitorTeamSettings:{name:"GetChangeMonitorTeamSettings",I:_.uQt,O:_.aEL,kind:a.I.Unary},cancelAutomationRun:{name:"CancelAutomationRun",I:_.uH2,O:_.MyF,kind:a.I.Unary},cancelAllAutomationRuns:{name:"CancelAllAutomationRuns",I:_.EpA,O:_.ETz,kind:a.I.Unary},retryAutomationRun:{name:"RetryAutomationRun",I:_.MNs,O:_.AV1,kind:a.I.Unary},listAutomationMemories:{name:"ListAutomationMemories",I:_.wyY,O:_.mDo,kind:a.I.Unary},getAutomationMemory:{name:"GetAutomationMemory",I:_.a_Y,O:_.oZ8,kind:a.I.Unary},updateAutomationMemory:{name:"UpdateAutomationMemory",I:_.PL0,O:_.TAX,kind:a.I.Unary},deleteAutomationMemory:{name:"DeleteAutomationMemory",I:_.xld,O:_.RmH,kind:a.I.Unary},listWorkflowTemplates:{name:"ListWorkflowTemplates",I:_._oe,O:_.UL8,kind:a.I.Unary},getWorkflowTemplate:{name:"GetWorkflowTemplate",I:_.tqQ,O:_.Pgs,kind:a.I.Unary},createWorkflowFromTemplate:{name:"CreateWorkflowFromTemplate",I:_.LWk,O:_.dgz,kind:a.I.Unary},validateAutomationTools:{name:"ValidateAutomationTools",I:_.Qjm,O:_.eOx,kind:a.I.Unary},builderCompletion:{name:"BuilderCompletion",I:_.FFL,O:_.ZGp,kind:a.I.Unary},disableAutomationForTeamShutdown:{name:"DisableAutomationForTeamShutdown",I:_.D$6,O:_.NB_,kind:a.I.Unary},getSentryAuthUrl:{name:"GetSentryAuthUrl",I:_.qqZ,O:_.k$4,kind:a.I.Unary},connectSentryCallback:{name:"ConnectSentryCallback",I:_.OtM,O:_.WPw,kind:a.I.Unary},getSentryStatus:{name:"GetSentryStatus",I:_.LSQ,O:_.FWA,kind:a.I.Unary},getSentryProjects:{name:"GetSentryProjects",I:_.Blo,O:_.huS,kind:a.I.Unary},disconnectSentry:{name:"DisconnectSentry",I:_.T7b,O:_.dDD,kind:a.I.Unary}}},C={typeName:"aiserver.v1.BidiService",methods:{bidiAppend:{name:"BidiAppend",I:i.Qd,O:i.yq,kind:a.I.Unary}}};var v=r("../proto/dist/generated/aiserver/v1/server_config_pb.js");const E={typeName:"aiserver.v1.ServerConfigService",methods:{getServerConfig:{name:"GetServerConfig",I:v.D8,O:v.Ld,kind:a.I.Unary},resolveNewRepoFlowBackendProbe:{name:"ResolveNewRepoFlowBackendProbe",I:v.Gt,O:v.nM,kind:a.I.Unary},getNewRepoFlowConfig:{name:"GetNewRepoFlowConfig",I:v.Yu,O:v.MO,kind:a.I.Unary}}};var S=r("../../../../../../../../../../<build path>"),I=r("../../../../../../../../../../<build path>"),B=r("../../../../../../../../../../<build path>"),k=r("./src/analytics.ts"),P=r("./src/auth-refresh.ts");class x{map(t){if(t.name===g.methods.run.name)return{name:"RunSSE",I:i.$r,O:t.O,kind:a.I.ServerStreaming};throw new Error(`Unknown method: ${t.name}`)}}var R=r("./src/bridge/proxy-http2-session-manager.ts"),J=r("./src/debug.ts"),T=r("../../../../../../../../../../<build path>"),q=r("../../../../../../../../../../<build path>"),j=r("../../../../../../../../../../<build path>"),D=r("../../../../../../../../../../<build path>");async function Q(t){const e=new o.T(`HTTP ${t.status}: ${t.statusText}`,(0,j.q)(t.status));let r;try{r=await t.text()}catch{return e}if(0===r.trim().length)return e;try{return(0,D.Nn)(JSON.parse(r),t.headers,e)}catch{return new o.T(`HTTP ${t.status}: ${t.statusText} - ${r.slice(0,512)}`,(0,j.q)(t.status))}}class N{constructor(t){this.options=t}get interceptors(){return this.options.interceptors||[]}get baseUrl(){return this.options.baseUrl}async unary(t,e,r,n,s,i,a){return await(0,q.L)({interceptors:this.interceptors,signal:r,timeoutMs:n,req:{stream:!1,service:t,method:e,url:`${this.baseUrl}/${t.typeName}/${e.name}`,init:{},header:new Headers(s),contextValues:a??(0,T.k)(),message:i},next:async r=>{const n={"Content-Type":"application/json"};r.header.forEach(((t,e)=>{n[e]=t}));const s=await fetch(r.url,{method:"POST",body:JSON.stringify(r.message),headers:n,signal:r.signal});if(!s.ok)throw await Q(s);return{stream:!1,service:t,method:e,header:s.headers,trailer:new Headers,message:e.O.fromJson(await s.json(),{ignoreUnknownFields:!0})}}})}async stream(t,e,r,n,s,i,a){return await(0,q.u)({interceptors:this.interceptors,signal:r,timeoutMs:n,req:{stream:!0,service:t,method:e,url:`${this.baseUrl}/${t.typeName}/${e.name}`,init:{method:"POST",redirect:"error",mode:"cors"},header:(()=>{const t=new Headers({"Content-Type":"application/connect+json"});return s&&new Headers(s).forEach(((e,r)=>{t.set(r,e)})),t})(),contextValues:a??(0,T.k)(),message:i},next:async r=>{const n=this.createConnectStreamingBody(r.message,e),s={};r.header.forEach(((t,e)=>{s[e]=t}));const i=await fetch(r.url,{method:"POST",body:n,headers:s,signal:r.signal});if(!i.ok)throw await Q(i);return{stream:!0,service:t,method:e,header:i.headers,trailer:new Headers,message:this.parseConnectStreamingResponse(i,e)}}})}createConnectStreamingBody(t,e){const r=new TextEncoder;return new ReadableStream({async start(n){try{for await(const s of t){const t=new e.I(s).toJson(),i=r.encode(JSON.stringify(t)),a=new Uint8Array(5+i.length);a[0]=0;const o=i.length;a[1]=o>>>24&255,a[2]=o>>>16&255,a[3]=o>>>8&255,a[4]=255&o,a.set(i,5),n.enqueue(a)}n.close()}catch(t){n.error(t)}}})}parseConnectStreamingResponse(t,e){const r=new TextDecoder;return{async*[Symbol.asyncIterator](){if(!t.body)throw new Error("No response body");const n=t.body.getReader();let s=new Uint8Array(0);try{for(;;){const{done:t,value:i}=await n.read();if(t)break;const a=new Uint8Array(s.length+i.length);for(a.set(s),a.set(i,s.length),s=a;s.length>=5;){const t=s[0],n=s[1]<<24|s[2]<<16|s[3]<<8|s[4];if(s.length<5+n)break;const i=s.slice(5,5+n);if(s=s.slice(5+n),2&t){const t=JSON.parse(r.decode(i));if(t.error){const e=new Error(t.error.message||"Stream error");throw void 0!==t.error.code&&(e.code=t.error.code),e}return}{const t=JSON.parse(r.decode(i)),n=e.O.fromJson(t,{ignoreUnknownFields:!0});yield n}}}}finally{n.releaseLock()}}}}}var O=r("./src/netsim.ts"),M=r("./src/privacy.ts"),U=r("./src/statsig.ts"),L=r("./src/statsig-overrides.ts"),F=r("./src/structured-log.ts"),$=r("./src/telemetry-context.ts"),G=r("./src/utils/service-urls.ts");const K=1e3;function H(...t){for(const e of t){const t=process.env[e];if(void 0!==t&&""!==t.trim())return t}}function z(t,e,r){const n=r?.configProvider?.get().authInfo?.activeTeamId;return s=>async i=>{const a=r?.apiUrl??r?.baseUrl;if(a&&r?.configProvider)try{(0,M.Hg)({credentialManager:t,apiUrl:a,configProvider:r.configProvider})}catch{}const o=r?.baseUrl||"",c=await(0,P.uX)(t,o);null!=c&&i.header.set("authorization",`Bearer ${c}`);const u=(()=>{try{const t=r?.configProvider?.get().privacyCache?.ghostMode;return"boolean"!=typeof t||t}catch{return!0}})(),l=(0,$.zP)().surface,d=r?.configProvider?.get()?.channel,m=d&&!["prod","prod-stable-internal"].includes(d)?`-${d}`:"";i.header.set("x-ghost-mode",u?"true":"false"),(0,f._5)(i.header),(0,f.EL)(i.header,n),i.header.set("x-cursor-client-version",`cli-2026.10.01-e373342${m}`),i.header.set("x-cursor-client-type",l),function(t){const e=(0,L.Y1)();void 0!==e&&null===t.get("x-dev-experiment-overrides")&&t.set("x-dev-experiment-overrides",e)}(i.header),i.header.get("x-request-id")||i.header.set("x-request-id",crypto.randomUUID());const p={requestId:i.header.get("x-request-id"),inner:i},h=await e(p,(t=>s(t.inner)));return h}}function W(t,e,r,n,s){const i=z(t,s??f.Wn,{baseUrl:e,configProvider:n}),a=(0,B.wQ)({baseUrl:e,httpVersion:"1.1",interceptors:[i],sendCompression:B.JY,nodeOptions:{rejectUnauthorized:!r,autoSelectFamilyAttemptTimeout:K}});return(0,I.UU)(E,a)}function Y(t,e,n){const s=z(t,f.Wn,{baseUrl:e,configProvider:n}),i=new N({baseUrl:e,interceptors:[s]});let a;return()=>(a??=Promise.all([r.e(1326),r.e(159),r.e(5380)]).then(r.bind(r,"../proto/dist/generated/aiserver/v1/background_composer_connect.js")).then((t=>(0,I.UU)(t.BackgroundComposerService,i))).catch((t=>{throw a=void 0,t})),a)}function V(t,e,n){const s=z(t,f.Wn,{baseUrl:e,configProvider:n}),i=new N({baseUrl:e,interceptors:[s]});let a;return()=>(a??=Promise.all([r.e(1326),r.e(5720)]).then(r.bind(r,"../proto/dist/generated/aiserver/v1/agent_store_connect.js")).then((t=>(0,I.UU)(t.AgentStoreService,i))).catch((t=>{throw a=void 0,t})),a)}function X(t){switch(t){case v.fG.FORCE_ALL_DISABLED:return"FORCE_ALL_DISABLED";case v.fG.FORCE_BIDI_DISABLED:return"FORCE_BIDI_DISABLED";case v.fG.FORCE_ALL_ENABLED:return"FORCE_ALL_ENABLED";case v.fG.FORCE_BIDI_ENABLED:return"FORCE_BIDI_ENABLED";case v.fG.UNSPECIFIED:return"UNSPECIFIED";default:return"UNKNOWN"}}function Z(t,e){const r=(()=>{try{const t=e.configProvider?.get().privacyCache?.ghostMode;return"boolean"!=typeof t||t}catch{return!0}})(),s=e.configProvider?.get().network.useHttp1ForAgent??!1,i=function(t,e){switch(e){case v.fG.FORCE_ALL_DISABLED:return{useHttp1:!0,reason:"server_force_all_disabled"};case v.fG.FORCE_BIDI_DISABLED:return{useHttp1:!0,reason:"server_force_bidi_disabled"};case v.fG.FORCE_ALL_ENABLED:return{useHttp1:!1,reason:"server_force_all_enabled"};case v.fG.FORCE_BIDI_ENABLED:return{useHttp1:!1,reason:"server_force_bidi_enabled"};case v.fG.UNSPECIFIED:return{useHttp1:t,reason:t?"local_config_http1":"default_http2"};default:return{useHttp1:t,reason:t?"unknown_server_config_local_http1":"unknown_server_config_default_http2"}}}(s,e.serverHttp2Config),a=i.useHttp1;!s&&a?(0,J.cY)("serverConfig.agentHttp1Override","enabled"):s&&!a&&(0,J.cY)("serverConfig.agentHttp2Override","enabled");const o=e.agentEndpoint??(0,G.bd)(e.backendUrl,r,e.serverAgentUrlConfig,a);(0,J.W6)("serverConfig.agentTransport",{httpVersion:a?"1.1":"2",reason:i.reason,localUseHttp1ForAgent:s,serverHttp2Config:{value:e.serverHttp2Config,name:X(e.serverHttp2Config)},agentUrl:o,hasAgentEndpointOverride:void 0!==e.agentEndpoint,hasServerAgentUrlConfig:void 0!==e.serverAgentUrlConfig},"INFO");const c=z(t,e.requestMiddleware??f.Wn,{baseUrl:o,apiUrl:e.backendUrl,configProvider:e.configProvider}),u=t=>async e=>(e.header.set("x-cursor-streaming","true"),await t(e)),l=(0,O.n_)(),d=new URL(o),h="https:"===d.protocol;let A;if(a){const t=(0,B.wQ)({baseUrl:o,httpVersion:"1.1",interceptors:l?[u,c,l]:[u,c],sendCompression:B.JY,nodeOptions:{...h&&{protocol:"https:",rejectUnauthorized:!e.insecure},autoSelectFamilyAttemptTimeout:K}}),r=(0,I.UU)(C,t);A=new m(new x,r,t,(t=>(0,J.cY)("bidi-error",t)))}else{const t={...h&&{protocol:"https:",rejectUnauthorized:!e.insecure},autoSelectFamilyAttemptTimeout:K},r=function(){const t=(0,U.z)("http2_agent_connection_pool_config","poolSize",4);return"number"!=typeof t||!Number.isFinite(t)||t<=0?4:Math.max(1,Math.floor(t))}(),n=function(t){switch(t.protocol){case"https:":return H("HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy");case"http:":return H("HTTP_PROXY","http_proxy");default:return}}(d),s=[];for(let e=0;e<r;e++)s.push(void 0!==n?new R.A({authority:o,proxyUrl:n,http2SessionOptions:t}):new B.gE(o,{pingIntervalMs:1e4,pingTimeoutMs:2e4,pingIdleConnection:!0},t));let i=0;A=(0,B.wQ)({baseUrl:o,httpVersion:"2",interceptors:l?[c,l]:[c],sendCompression:B.JY,sessionManager:{get authority(){return new URL(o).origin},request(t,e,n,a){const o=s[i%r];return i++,o.request(t,e,n,a)},notifyResponseByteRead(t){}},nodeOptions:{...h&&{protocol:"https:",rejectUnauthorized:!e.insecure},autoSelectFamilyAttemptTimeout:K}})}const b=(0,p.Zj)(g,A);return new n.PW(b,o)}function tt(t,e){const r=z(t,f.Wn,{baseUrl:e.endpoint,configProvider:e.configProvider});e.insecure&&e.endpoint.startsWith("https:")&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const n=new N({baseUrl:e.endpoint,interceptors:[r]});return(0,I.UU)(y,n)}function et(t,e){const r=tt(t,e);(0,k.Bu)(r,t),(0,F.MC)(r,t)}function rt(t,e){const r=z(t,e.requestMiddleware??f.Wn,{baseUrl:e.backendUrl,configProvider:e.configProvider}),n="https:"===new URL(e.backendUrl).protocol,s=(0,O.n_)();return(0,B.wQ)({baseUrl:e.backendUrl,httpVersion:"1.1",interceptors:s?[r,s]:[r],sendCompression:B.JY,nodeOptions:{...n&&{protocol:"https:",rejectUnauthorized:!e.insecure},autoSelectFamilyAttemptTimeout:K}})}function nt(t,e){const r=rt(t,e);return(0,I.UU)(A.E,r)}function st(t,e){const r=rt(t,e);return(0,I.UU)(w,r)}function it(t){return{async evaluatePromptHook(e,r){const n=S.WT.fromJson(r.hookInputJson),s=await t.evaluatePromptHook(e,{prompt:r.prompt,hookInputJson:n,modelName:r.modelName});return{ok:s.ok,reason:s.reason}}}}}

Requested model construction

Source: 9577.index.js (Agent CLI) · bytes 22648–24344 · SHA-256 3aa2adc0acea…

Minified Agent CLI webpack module ./src/model-request-format.ts (1,696 characters), the code behind the requested model construction. Identifiers are minified; the exact shipped code is below.

Exact shipped text
"./src/model-request-format.ts"(e,t,r){r.d(t,{K:()=>a,U:()=>i});var s=r("../cursor-config/dist/schema.js"),n=r("../proto/dist/generated/agent/v1/agent_pb.js"),o=r("../proto/dist/generated/agent/v1/requested_model_pb.js");function a(e){return void 0!==e.requestedModel?{modelDetails:void 0,requestedModel:e.requestedModel}:{modelDetails:e.modelDetails,requestedModel:void 0}}function i(e){const t=function(e){const t=e.configProvider;if(void 0===t)return{};const r=(0,s.cy)(t.get());if("default"===r)return{};if("inherit"===r||"disabled"===r)return{subagentModelOverrides:[new n.Bj({subagentType:"explore",selection:{case:r,value:!0}})]};const a=r.parameters??e.modelManager.getParametersForModel(r.modelId,t);return{subagentModelOverrides:[new n.Bj({subagentType:"explore",selection:{case:"model",value:new o.G4({modelId:r.modelId,maxMode:r.maxMode??!0===e.parentMaxMode,parameters:a.map((e=>new o.SR({id:e.id,value:e.value})))})}})]}}({modelManager:e.modelManager,configProvider:e.configProvider,parentMaxMode:e.parentMaxMode}),r=e.modelManager.getParameterizedModels(),a=r.filter((e=>e.supportsAgent&&(e.defaultOn??!1)));if(r.length>0&&a.length>0)return{selectedSubagentModels:a.map((t=>function(e){return new o.G4({modelId:e.model.name,maxMode:e.maxMode,parameters:e.parameters.map((e=>new o.SR({id:e.id,value:e.value})))})}({model:t,parameters:void 0!==e.configProvider?e.modelManager.getParametersForModel(t.name,e.configProvider):[],maxMode:!0===e.parentMaxMode}))),...t};if(r.length>0)return t;const i=e.modelManager.getAvailableModels().filter((e=>e.modelId)).map((t=>new n.Gm({modelId:t.modelId,maxMode:!0===e.parentMaxMode})));return i.length>0?{selectedSubagentModelsLegacy:i,...t}:t}}

Service endpoint selection

Source: index.js (Agent CLI) · bytes 2694310–2696014 · SHA-256 7e688a92b14b…

Minified Agent CLI webpack module ./src/utils/service-urls.ts (1,704 characters), the code behind the service endpoint selection. Identifiers are minified; the exact shipped code is below.

Exact shipped text
"./src/utils/service-urls.ts"(t,e,r){"use strict";r.d(e,{Uz:()=>n,bd:()=>l,e9:()=>c,ju:()=>s,qM:()=>o,to:()=>u});const n="prod",s={prod:{apiUrl:"https://api2.cursor.sh",websiteUrl:"https://cursor.com",metricsUrl:"https://api3.cursor.sh"},playground:{apiUrl:"https://api.playground.cursor.sh",websiteUrl:"https://playground.cursor.com"},staging:{apiUrl:"https://staging.cursor.sh",websiteUrl:"https://staging.cursor.sh"},"dev-staging":{apiUrl:"https://dev-staging.cursor.sh",websiteUrl:"https://dev-staging.cursor.sh"},localhost:{apiUrl:"https://localhost:8000",websiteUrl:"https://localhost:8000"}};function i(t,e){try{const r=new URL(t);if("reject"===e&&(r.hash||r.search||r.username||r.password))return;return r.origin.toLowerCase()}catch{return}}function a(t){const e=i(t,"reject");if(void 0!==e)for(const t of Object.keys(s)){const{apiUrl:r,websiteUrl:n}=s[t];if(i(r,"reject")===e||i(n,"reject")===e)return t}}function o(t){const e=t?.websiteUrl??process.env.CURSOR_WEBSITE_URL;if(e?.includes("#"))throw new Error(`Invalid website URL "${e}": URLs must not contain a fragment ("#").`);const r=c(t?.apiUrl),n=a(r);if(void 0!==n){const t=s[n];return{apiUrl:t.apiUrl,websiteUrl:e??t.websiteUrl}}if(r.includes("#"))throw new Error(`Invalid API URL "${r}": URLs must not contain a fragment ("#").`);return{apiUrl:r,websiteUrl:e??i(r,"strip")??r}}function c(t){if(t)return t;return process.env.CURSOR_API_ENDPOINT||s[n].apiUrl}function u(t){const e=a(c(t));return void 0===e?void 0:s[e].metricsUrl}function l(t,e,r,n){return t.includes("localhost")||t.includes("lclhst.build")||t.includes("staging.cursor.sh")||t.includes("dev-staging.cursor.sh")||n?t:r?.agentUrl&&r?.agentnUrl?e?r.agentUrl:r.agentnUrl:t}}

Daemon request mapping

Source: extensions/cursor-agent-host/dist/agent-host-daemon/dist/bin/daemon.cjs (desktop) · bytes 26203247–26209529 · SHA-256 560ba5dd454e…

Unminified desktop source for src/map-request.ts (6,282 characters), the code behind the daemon request mapping. It reads as shipped, below.

Exact shipped text
// src/map-request.ts
function toCreateSessionRequest(req) {
  const sessionOptions = req.sessionOptions;
  const workspacePaths = sessionOptions?.workspacePaths ?? [];
  const isGlassRoot = sessionOptions?.isGlassRoot === true;
  if (sessionOptions === void 0 || workspacePaths.length === 0 && !isGlassRoot) {
    throw new ConnectError(
      "CreateSession requires session_options.workspace_paths with at least one absolute path",
      Code.InvalidArgument
    );
  }
  for (const workspacePath of workspacePaths) {
    const trimmed = workspacePath.trim();
    if (trimmed.length === 0 || !(0, import_node_path97.isAbsolute)(trimmed)) {
      throw new ConnectError(
        "CreateSession requires session_options.workspace_paths with at least one absolute path",
        Code.InvalidArgument
      );
    }
  }
  const clientInstanceId = req.clientInstanceId?.trim() ?? "";
  if (isGlassRoot && workspacePaths.length === 0 && clientInstanceId.length === 0) {
    throw new ConnectError("Glass CreateSession requires client_instance_id", Code.InvalidArgument);
  }
  return {
    sessionId: req.sessionId,
    initialHistory: req.initialHistory,
    sessionOptions,
    clientInstanceId: req.clientInstanceId,
    ...clientInstanceId.length > 0 ? { owningClientInstanceId: clientInstanceId } : {}
  };
}
function toForkSessionRequest(req) {
  return {
    sessionId: req.sessionId,
    throughTurnId: req.throughTurnId
  };
}
function toListSessionsRequest(req) {
  const workspacePathsFilter = requireWorkspacePathsFilter(req.workspacePathsFilter);
  const ownerClientInstanceId = req.ownerClientInstanceId?.trim() || void 0;
  return {
    includeChildren: req.includeChildren,
    parentSessionId: req.parentSessionId,
    limit: req.limit,
    workspacePathsFilter,
    matchAnyWorkspaceRoot: req.matchAnyWorkspaceRoot,
    ...ownerClientInstanceId === void 0 ? {} : { ownerClientInstanceId },
    includeOwnerUnrootedSessions: req.includeOwnerUnrootedSessions
  };
}
function toListWorkspacesRequest(_req) {
  return {};
}
function toWatchSessionsRequest(req) {
  const workspacePathsFilter = requireWorkspacePathsFilter(req.workspacePathsFilter);
  const ownerClientInstanceId = req.ownerClientInstanceId?.trim() || void 0;
  return {
    workspacePathsFilter,
    matchAnyWorkspaceRoot: req.matchAnyWorkspaceRoot,
    ...ownerClientInstanceId === void 0 ? {} : { ownerClientInstanceId },
    includeOwnerUnrootedSessions: req.includeOwnerUnrootedSessions
  };
}
function toHasSessionRequest(req) {
  return { sessionId: req.sessionId };
}
function requireWorkspacePathsFilter(filter3) {
  const normalized = [];
  for (const path53 of filter3 ?? []) {
    if (path53.length === 0) {
      continue;
    }
    if (!normalized.includes(path53)) {
      normalized.push(path53);
    }
  }
  if (normalized.length === 0) {
    throw new ConnectError("workspace_paths_filter must be non-empty", Code.InvalidArgument);
  }
  return normalized;
}
function toSendMessageRequest(req) {
  return {
    sessionId: req.sessionId,
    text: req.text,
    messageId: req.messageId,
    modelId: req.modelId,
    modelDetails: req.modelDetails,
    requestedModel: req.requestedModel,
    turnOptions: req.turnOptions
  };
}
function toSendActionRequest(req) {
  if (req.action === void 0) {
    throw new ConnectError("action is required", Code.InvalidArgument);
  }
  return {
    sessionId: req.sessionId,
    action: req.action,
    modelId: req.modelId,
    modelDetails: req.modelDetails,
    requestedModel: req.requestedModel,
    turnOptions: req.turnOptions,
    baseHistory: req.baseHistory,
    delivery: req.delivery,
    replaceQueuedTurnId: req.replaceQueuedTurnId,
    requestContextDecoration: req.requestContextDecoration
  };
}
function toDeleteSessionRequest(req) {
  return { sessionId: req.sessionId };
}
function toInterruptTurnRequest(req) {
  return {
    sessionId: req.sessionId,
    turnId: req.turnId,
    reason: req.reason,
    sessionTree: req.sessionTree,
    initiatedBy: req.initiatedBy
  };
}
function toCancelQueuedTurnRequest(req) {
  return {
    sessionId: req.sessionId,
    turnId: req.turnId,
    reason: req.reason,
    initiatedBy: req.initiatedBy
  };
}
function toRespondToInteractionRequest(req) {
  if (req.response === void 0) {
    throw new ConnectError("response is required", Code.InvalidArgument);
  }
  return {
    sessionId: req.sessionId,
    interactionId: req.interactionId,
    response: req.response
  };
}
function toWatchInteractionsRequest(req) {
  return { sessionId: req.sessionId };
}
function toWatchBackgroundWorkRequest(req) {
  return {
    sessionId: req.sessionId,
    kind: req.kind,
    state: req.state,
    ownerId: req.ownerId
  };
}
function toWatchTurnLifecycleRequest(req) {
  return { sessionId: req.sessionId };
}
function toAbortBackgroundWorkRequest(req) {
  return {
    sessionId: req.sessionId,
    workId: req.workId
  };
}
function toAbortAllBackgroundWorkRequest(req) {
  return {
    sessionId: req.sessionId,
    kind: req.kind,
    state: req.state,
    ownerId: req.ownerId
  };
}
function toAttachSessionRequest(req) {
  return {
    sessionId: req.sessionId,
    lastEventId: req.lastEventId,
    backgroundTaskCompletionsOnly: req.backgroundTaskCompletionsOnly,
    clientInstanceId: req.clientInstanceId
  };
}
function toGetSessionBlobsRequest(req) {
  return {
    sessionId: req.sessionId,
    blobIds: req.blobIds,
    maxResponseBytes: req.maxResponseBytes
  };
}
function toReadFileRequest(req) {
  return {
    path: req.path,
    readOffset: req.readOffset,
    readLimit: req.readLimit,
    ...req.cachedMtimeMs === void 0 ? {} : { cachedMtimeMs: req.cachedMtimeMs }
  };
}
function toWatchShellOutputRequest(req) {
  return {
    sessionId: req.sessionId,
    shellId: req.shellId,
    ...req.includeSnapshot === void 0 ? {} : { includeSnapshot: req.includeSnapshot },
    ...req.fromOutputOffset === void 0 ? {} : { fromOutputOffset: req.fromOutputOffset }
  };
}
function toWriteShellInputRequest(req) {
  return {
    sessionId: req.sessionId,
    shellId: req.shellId,
    data: req.data
  };
}
var import_node_path97;
var init_map_request = __esm({
  "src/map-request.ts"() {
    "use strict";
    import_node_path97 = require("node:path");
    init_esm3();
  }
});

Daemon RPC service

Source: extensions/cursor-agent-host/dist/agent-host-daemon/dist/bin/daemon.cjs (desktop) · bytes 26232244–26233280 · SHA-256 cb078e5b6d3b…

Unminified desktop source for src/rpc.ts (1,036 characters), the code behind the daemon RPC service. It reads as shipped, below.

Exact shipped text
// src/rpc.ts
async function unaryRpc(handlerCtx, run) {
  throwIfHandlerCanceled(handlerCtx);
  const attached = attachHandlerContext(handlerCtx);
  try {
    throwIfHandlerCanceled(handlerCtx);
    return await run(attached.ctx);
  } catch (error3) {
    throw toConnectError2(error3);
  } finally {
    attached.detach();
  }
}
async function* streamRpc(handlerCtx, run, map4) {
  throwIfHandlerCanceled(handlerCtx);
  const attached = attachHandlerContext(handlerCtx);
  try {
    throwIfHandlerCanceled(handlerCtx);
    for await (const item of run(attached.ctx)) {
      yield map4(item);
    }
  } catch (error3) {
    throw toConnectError2(error3);
  } finally {
    attached.detach();
  }
}
function throwIfHandlerCanceled(handlerCtx) {
  if (!handlerCtx.signal.aborted) {
    return;
  }
  const reason = handlerCtx.signal.reason;
  throw toConnectError2(reason instanceof Error ? reason : rpcCanceledError());
}
var init_rpc = __esm({
  "src/rpc.ts"() {
    "use strict";
    init_errors8();
    init_rpc_context();
  }
});

Reasoning events

ACP reasoning stream projection

Source: 3351.index.js (Agent CLI) · bytes 1439–19708 · SHA-256 65584da9dec9…

Minified Agent CLI webpack module ./src/acp/agent-session.ts (17,636 characters), the code behind the ACP reasoning stream projection. Identifiers are minified; the exact shipped code is below.

Exact shipped text
"./src/acp/agent-session.ts"(e,t,s){s.a(e,(async(e,a)=>{try{s.d(t,{m:()=>W});var n=s("node:fs/promises"),o=s("node:url"),r=s("../agent-client/dist/index.js"),i=s("../agent-core/dist/conversation-actions/controlled.js"),l=s("../agent-core/dist/domain-utils.js"),c=s("../agent-core/dist/interaction-queries.js"),d=s("../proto/dist/generated/agent/v1/agent_pb.js"),u=s("../proto/dist/generated/agent/v1/agent_service_pb.js"),h=s("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),p=s("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),g=s("../proto/dist/generated/agent/v1/selected_context_pb.js"),m=s("../../../../../../../../../../<build path>"),f=s("../../../../../../../../../../<build path>"),v=s("./src/analytics.ts"),C=s("./src/bedrock/requested-model.ts"),w=s("./src/commands/custom-commands.ts"),b=s("./src/commands/prompt-skill-references.ts"),I=s("./src/debug.ts"),y=s("./src/internal-error-telemetry.ts"),S=s("./src/model-request-format.ts"),T=s("./src/state/session.ts"),P=s("./src/utils/blob-encryption-key-header.ts"),k=s("./src/utils/clipboard.ts"),M=s("./src/utils/eval-hardening.ts"),A=s("./src/utils/git.ts"),x=s("./src/utils/interaction-responses.ts"),_=s("./src/utils/interaction-utils.ts"),R=s("./src/utils/terminal-title.ts"),j=s("./src/utils/url-utils.ts"),q=s("./src/acp/interaction-handlers/ask-question-handler.ts"),U=s("./src/acp/interaction-handlers/create-plan-handler.ts"),E=s("./src/acp/resource-link-security.ts"),F=s("./src/acp/session-update-presenter.ts"),O=s("./src/acp/subagent-completion-drain.ts"),N=s("./src/acp/subagent-history.ts"),$=s("./src/acp/tool-call-presentation.ts"),L=e([R]),D=L.then?(await L)():L;R=D[0];const V=2e4,Y=1e4;class W{constructor(e,t,s,a,n,o,r,i,l={}){this.lastRequestId=null,this.pendingAutoNamePromise=null,this.commandsAndSkillsPromise=null,this.connection=e,this.sessionId=t,this.pendingPromptCancel=null,this.sharedServices=s,this.ctx=a,this.agentStore=n,this.resources=o,this.mcpLease=r,this.currentModel=i,this.subagentsEnabled=l.subagentsEnabled??!1,this.backgroundWorkRegistry=l.backgroundWorkRegistry,this.subagentPublisher=l.subagentPublisher,this.presenter=new F.A(e,t,$.Le)}setCurrentModel(e){this.currentModel=e}getCurrentModel(){return this.currentModel}isSubagentsEnabled(){return this.subagentsEnabled}buildRequestedModel(){return this.sharedServices.modelManager.buildRequestedModel()}async buildBedrockRequestedModelForRun(e){const t=e?.modelId??this.currentModel.modelId,s=e?.maxMode??this.currentModel.maxMode;return(0,C.c)(new d.Gm({...this.currentModel,modelId:t,maxMode:s}),this.sharedServices.configProvider,this.sharedServices.credentialManager,this.sharedServices.dashboardClient,e)}getProjectRoot(){return(0,A.ky)(process.cwd())||process.cwd()}loadCommandsAndSkills(){return this.commandsAndSkillsPromise??=(async()=>{const e=new w.FD(this.sharedServices.dashboardClient),t=await e.loadCommands(this.getProjectRoot(),{includeSkills:!0});return{loader:e,slashCommands:t}})().catch((e=>{throw this.commandsAndSkillsPromise=null,e})),this.commandsAndSkillsPromise}setMode(e){this.agentStore.setMetadata("mode",e);const t=(0,_.mb)(e);this.sendCurrentModeUpdate(t).catch((e=>{(0,I.cY)("Failed to send mode update:",e)}))}getCliMode(){return this.agentStore.getMetadata("mode")}async sendCurrentModeUpdate(e){await this.sendSessionUpdate({sessionUpdate:"current_mode_update",currentModeId:e})}async sendSessionUpdate(e){await this.presenter.sendSessionUpdate(e)}async maybeAutoNameSession(e){const t=e.trim();if(0!==t.length&&!(0,R.iq)(this.agentStore.getMetadata("name")))return this.pendingAutoNamePromise||(this.pendingAutoNamePromise=(async()=>{try{const e=await this.sharedServices.aiServerClient.nameAgent(new u.Il({userMessage:t})),s=e.name?.trim();if(!(0,R.iq)(s))return;if((0,R.iq)(this.agentStore.getMetadata("name")))return;this.agentStore.setMetadata("name",s),await this.sendSessionUpdate({sessionUpdate:"session_info_update",title:s})}catch(e){(0,I.cY)("ACP auto-name failed",{sessionId:this.sessionId,error:e instanceof Error?e.message:String(e)})}finally{this.pendingAutoNamePromise=null}})()),this.pendingAutoNamePromise}async sendAvailableCommands(){const{slashCommands:e}=await this.loadCommandsAndSkills(),t={sessionUpdate:"available_commands_update",availableCommands:[{name:"copy-request-id",description:"Copy the last request ID to clipboard"},...e.map((e=>({name:e.id,description:e.description||""})))]};(0,I.cY)("Sending available commands:",t),await this.sendSessionUpdate(t),(0,I.cY)("Available commands sent successfully")}async replayConversationHistory(e){let t;try{t=await this.agentStore.getFullConversation(e)}catch(e){return void(0,I.cY)("ACP loadSession history replay failed to load conversation",{sessionId:this.sessionId,error:e instanceof Error?e.message:String(e)})}const s=t.turns??[],a=this.subagentsEnabled&&this.subagentPublisher?new N.g(this.agentStore.getConversationStateStructure()):void 0;for(let e=0;e<s.length;e++){const t=s[e];if("agentConversationTurn"===t.turn.case)try{await this.replayAgentTurn(t.turn.value,e,a)}catch(t){(0,I.cY)("ACP loadSession history replay failed for turn",{sessionId:this.sessionId,turnIndex:e,error:t instanceof Error?t.message:String(t)})}}}async replayAgentTurn(e,t,s){const a=e.userMessage?.text??"";a.trim().length>0&&await this.sendSessionUpdate({sessionUpdate:"user_message_chunk",content:{type:"text",text:a}});const n=e.userMessage?.selectedContext?.selectedImages??[];for(const e of n)"data"===e.dataOrBlobId.case&&await this.sendSessionUpdate({sessionUpdate:"user_message_chunk",content:{type:"image",data:Buffer.from(e.dataOrBlobId.value).toString("base64"),mimeType:e.mimeType}});for(let a=0;a<e.steps.length;a++){const n=e.steps[a];switch(n.message.case){case"assistantMessage":{const e=n.message.value.text;e.length>0&&await this.sendAgentMessageChunk(e);break}case"thinkingMessage":{const e=n.message.value.text;e.length>0&&await this.sendSessionUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:e}});break}case"toolCall":{const e=`replay-${t}-${a}`;await this.replayToolCall(n.message.value,e),await this.replaySubagentLifecycle(s,n.message.value,e);break}}}}async replaySubagentLifecycle(e,t,s){if(!e||!this.subagentPublisher)return;const a=e.describe(t);a&&await this.subagentPublisher.replayHistorical({agentId:a.agentId,toolCallId:s,parentAgentId:this.sessionId,name:a.name,task:a.task,model:a.model,state:a.state})}async replayToolCall(e,t){await this.presenter.presentCompletedToolCall(e,t)}async sendAgentMessageChunk(e){await this.presenter.sendAgentMessageChunk(e)}async handlePrompt(e){this.pendingPromptCancel?.();const[t,s]=this.ctx.withCancel();let a,n=!1;const o=this.subagentPublisher?.beginTurn(),r=()=>{if(void 0!==o)for(const e of this.subagentPublisher?.runIdsForTurn(o)??[])this.backgroundWorkRegistry?.abortWork(e)},i=()=>{!n&&this.subagentsEnabled&&(n=!0,r(),a=this.subagentPublisher?.whenAllTerminal({turn:o,timeoutMs:Y}))},l=()=>{i(),s()};this.pendingPromptCancel=l,t.signal.addEventListener("abort",i,{once:!0}),t.signal.aborted&&i();try{await this.processPrompt(e,t,o)}catch(e){if(!t.canceled)throw e}finally{this.pendingPromptCancel===l&&(this.pendingPromptCancel=null)}return t.canceled?(n&&(r(),a=this.subagentPublisher?.whenAllTerminal({turn:o,timeoutMs:Y})),await a,{stopReason:"cancelled"}):{stopReason:"end_turn"}}claimTaskToolCall(e,t){if(void 0===t)return;const s=e.message;"partialToolCall"!==s.case&&"toolCallStarted"!==s.case||"taskToolCall"===s.value.toolCall?.tool.case&&this.subagentPublisher?.claimToolCall(s.value.callId,t)}async processPrompt(e,t,s){const a=e.prompt||[],n=a.filter((e=>"text"===e.type)).map((e=>e.text)).join("\n")||"",o=a.filter((e=>"image"===e.type)),u=a.filter((e=>"resource_link"===e.type)),w=a.filter((e=>"resource"===e.type));if(!n.trim()&&0===o.length&&0===u.length&&0===w.length)return void await this.sendAgentMessageChunk("No prompt content provided.");const b=await this.handleSlashCommand(n.trim());if(b.handled)return;const k=await this.buildPromptResourceContext(u,w);this.maybeAutoNameSession(n);const A=k.length>0?[...n.length>0?[n,""]:[],"Additional ACP context:",...k].join("\n"):n;this.presenter.clear();const R={sendUpdate:async(e,t)=>{this.claimTaskToolCall(t,s),await this.presenter.presentInteractionUpdate(t)},query:async(e,t)=>{switch(t.query.case){case"askQuestionInteractionQuery":{const e=t.query.value;return e?(0,q.Z)({connection:this.connection,sessionId:this.sessionId,queryId:t.id,query:e,debugLog:I.cY}):c.x1.askQuestion(t.id,new h.tz({result:{case:"rejected",value:new h.ox({reason:"Missing ask-question query payload"})}}))}case"createPlanRequestQuery":{const e=t.query.value;if(!e)return c.x1.createPlan(t.id,new p.bK({result:{case:"error",value:new p.iY({error:"Missing create-plan query payload"})}}));try{await this.presenter.createPlanProgress.ensureToolCard(e.toolCallId,e.args?.name?`Create Plan: ${e.args.name}`:"Create Plan"),await this.presenter.createPlanProgress.emitProgress(e.toolCallId,"Processing plan...")}catch(t){(0,I.cY)("CreatePlan initial status update failed",{sessionId:this.sessionId,toolCallId:e.toolCallId,error:t instanceof Error?t.message:String(t)})}return(0,U.x)({connection:this.connection,sessionId:this.sessionId,queryId:t.id,query:e,conversationId:this.agentStore.getId(),emitProgress:async t=>this.presenter.createPlanProgress.emitProgress(e.toolCallId,t),sendPlanUpdate:async e=>this.sendSessionUpdate({sessionUpdate:"plan",entries:e}),debugLog:I.cY})}case"webFetchRequestQuery":{const e=t.query.value;if(!e)return c.x1.webFetchRejected(t.id,"Missing web-fetch query payload");const s=this.agentStore.getMetadata("isRunEverything");if(e.skipApproval)return(0,I.cY)("web-fetch-auto-approved-server-skip",{}),c.x1.webFetchApproved(t.id);if(s)return(0,I.cY)("web-fetch-auto-approved-acp-run-everything",{}),c.x1.webFetchApproved(t.id);const a=e.args?.url??"",n=(0,l.BF)(a),o=this.sharedServices.configProvider.get().permissions?.allow??[];return(0,j.hD)(n,o)?((0,I.cY)("web-fetch-auto-approved-acp-allowlist",{domain:n,url:a}),c.x1.webFetchApproved(t.id)):this.requestWebPermission({queryId:t.id,kind:"fetch",title:`Fetch ${a}`,allowlistValue:n})}case"webSearchRequestQuery":{const e=t.query.value;if(!e)return c.x1.webSearchRejected(t.id,"Missing web-search query payload");if((0,M.CR)())return c.x1.webSearchRejected(t.id,"Web search is disabled in this environment");if(this.agentStore.getMetadata("isRunEverything"))return(0,I.cY)("web-search-auto-approved-acp-run-everything",{}),c.x1.webSearchApproved(t.id);const s=this.sharedServices.configProvider.get();if(s.autoAcceptWebSearch)return(0,I.cY)("web-search-auto-approved-acp-config",{}),c.x1.webSearchApproved(t.id);const a=e.args?.searchTerm??"",n=s.permissions?.allow??[];return(0,j.lw)(a,n)?((0,I.cY)("web-search-auto-approved-acp-allowlist",{searchTerm:a}),c.x1.webSearchApproved(t.id)):this.requestWebPermission({queryId:t.id,kind:"search",title:`Web search: ${a}`,allowlistValue:a})}default:return(0,x.l)(t,{approveWebSearch:!1,approveWebFetch:!1,askQuestionRejectReason:"Questions skipped in ACP mode"})}}};let E;try{const e=o.map((e=>{const t=Buffer.from(e.data,"base64");return new g.d({dataOrBlobId:{case:"data",value:t},uuid:crypto.randomUUID(),mimeType:e.mimeType})})),s=new g.xv({selectedImages:e,cursorCommands:b.cursorCommands,selectedSkills:b.selectedSkills}),a=this.agentStore.getMetadata("mode")??"default",r=(0,_.cT)(a),l=new d.UserMessageAction({userMessage:new d.UserMessage({text:A,selectedContext:s,messageId:crypto.randomUUID(),mode:r})}),c=new i.h,u=this.buildRequestedModel(),h=await this.buildBedrockRequestedModelForRun(u)??u,p=(0,C.y)(this.currentModel,h),m=(0,S.K)({modelDetails:p,requestedModel:h}),f=new d.ConversationAction({action:{case:"userMessageAction",value:l}}),w={conversationId:this.agentStore.getId(),headers:(0,P.o)(this.agentStore),requestedModel:m.requestedModel,...(0,S.U)({modelManager:this.sharedServices.modelManager,configProvider:this.sharedServices.configProvider,parentMaxMode:h?.maxMode}),onConnectionStateChange:e=>{"reconnecting"===e.state?(0,I.cY)("Connection state: reconnecting"):"connected"===e.state&&(0,I.cY)("Connection state: connected")},onErrorNotRetried:e=>{(0,y.Z)({configProvider:this.sharedServices.configProvider,info:e})}};(0,v.sx)("cli.request.create",{length:n.length,model:h?.modelId??this.currentModel.modelId??"unknown",mode:a,conversationId:this.agentStore.getId()});const k=await this.mcpLease.getTools(t);E=e=>this.sharedServices.agentClient.run(t,this.agentStore.getConversationStateStructure(),e,m.modelDetails,R,this.resources,this.agentStore.getBlobStore(),c,this.agentStore,k,w),await E(f),this.lastRequestId=T.d.getLastParentAgentRequestId()}catch(e){if(this.lastRequestId=T.d.getLastParentAgentRequestId(),e instanceof r.cc||t.canceled)return;if(e instanceof r.ao){const t={login:"Please sign in to continue",upgrade:"Upgrade your plan to continue",payment:"Add a payment method to continue",config:"Check your settings to continue"}[e.action]??e.message;return void await this.sendAgentMessageChunk(`\n\n${t}`)}if(e instanceof m.T&&e.code===f.C.Unauthenticated)return void await this.sendAgentMessageChunk("\n\nError: [unauthenticated] Backend rejected authentication. Verify this is a User API Key for the same endpoint/environment, then rerun with --debug for request-level auth logs.");await this.sendAgentMessageChunk(`\n\nError: ${String(e)}`)}finally{if(E&&this.subagentsEnabled&&this.backgroundWorkRegistry){const e=E;await(0,O.t)({registry:this.backgroundWorkRegistry,conversationId:this.sessionId,signal:t.signal,runFollowup:e,liveChildren:{has:()=>this.subagentPublisher?.hasRunningChildren()??!1,onTerminal:e=>this.subagentPublisher?.onChildTerminal(e)??(()=>{})}}),t.canceled||void 0===s||await(this.subagentPublisher?.settledForTurn(s))}}}async handleSlashCommand(e){if("/copy-request-id"===e.toLowerCase().trim())return await this.handleCopyRequestId(),{handled:!0};const t={handled:!1,cursorCommands:[],selectedSkills:[]};if(!e.startsWith("/")&&!(0,b._)(e))return t;let s;try{({loader:s}=await this.loadCommandsAndSkills())}catch(e){return(0,I.cY)("Failed to load commands and skills for prompt",{sessionId:this.sessionId,error:e instanceof Error?e.message:String(e)}),t}return{handled:!1,cursorCommands:this.resolveLeadingSlashCommand(s,e),selectedSkills:(0,b.i)(s,e)}}resolveLeadingSlashCommand(e,t){if(!t.startsWith("/"))return[];const s=t.match(/^\/(\S+)(?:\s+(.*))?$/);if(!s)return[];const[,a,n]=s,o=n?.split(/\s+/).filter(Boolean)??[],r=e.getCommandById(a);return r?[(0,w.AD)(r,o)]:[]}async handleCopyRequestId(){const e=this.lastRequestId;e?await(0,k.e)(e)?await this.sendAgentMessageChunk(`Copied request ID: ${e}`):await this.sendAgentMessageChunk(`Request ID: ${e}`):await this.sendAgentMessageChunk("No request ID found. Submit a prompt first, then retry /copy-request-id.")}truncatePromptResourceContent(e){if(e.length<=V)return e;const t=e.length-V;return`${e.slice(0,V)}\n\n[...truncated ${t} characters]`}async buildPromptResourceContext(e,t){const s=[];for(const t of e){const e=await this.extractResourceLinkContext(t);e&&s.push(e)}for(const e of t){const t=this.extractEmbeddedResourceContext(e);t&&s.push(t)}return s}async extractResourceLinkContext(e){const t=e.uri,s=e.name;try{const e=new URL(t);if("file:"!==e.protocol)return`[ACP resource_link] ${s} (${t})`;const a=(0,o.fileURLToPath)(e),r=this.getProjectRoot(),[i,l]=await Promise.all([(0,E.h)(a),(0,E.h)(r)]);if(!(0,E.U)({pathToCheck:i,rootDirectory:l}))return(0,I.cY)("Skipping ACP resource_link outside project root",{uri:t,projectRoot:l}),`[ACP resource_link] ${s} (${t})`;const c=await(0,n.readFile)(i,"utf8");return[`[ACP resource_link] ${s} (${t})`,this.truncatePromptResourceContent(c)].join("\n")}catch(e){return(0,I.cY)("Failed to extract ACP resource_link context",{uri:t,error:e instanceof Error?e.message:String(e)}),`[ACP resource_link] ${s} (${t})`}}extractEmbeddedResourceContext(e){const t=e.resource,s=t.uri;return"text"in t?[`[ACP embedded_resource] ${s}`,this.truncatePromptResourceContent(t.text)].join("\n"):`[ACP embedded_resource] ${s} (binary content omitted)`}async requestWebPermission(e){const{queryId:t,kind:s,title:a,allowlistValue:n}=e,o="fetch"===s?"fetch":"search",r={sessionId:this.sessionId,toolCall:{toolCallId:`web_${s}_${t}`,title:a,kind:o,status:"pending"},options:[{optionId:"allow-once",name:"Allow once",kind:"allow_once"},{optionId:"allow-always",name:"Allow always",kind:"allow_always"},{optionId:"reject-once",name:"Reject",kind:"reject_once"}]};try{const e=await this.connection.requestPermission(r);if("cancelled"===e.outcome.outcome)return"fetch"===s?c.x1.webFetchRejected(t,"Cancelled"):c.x1.webSearchRejected(t,"Cancelled");if("selected"===e.outcome.outcome){const a=e.outcome.optionId,o="allow-once"===a||"allow-always"===a;if("allow-always"===a&&n){const e="fetch"===s?"WebFetch":"WebSearch";try{await(0,j.GJ)(this.sharedServices.permissionsProvider,e,n)}catch(e){(0,I.cY)(`web-${s}-allowlist-persist-failed`,e)}}return o?((0,I.cY)(`web-${s}-approved-by-client`,{}),"fetch"===s?c.x1.webFetchApproved(t):c.x1.webSearchApproved(t)):"fetch"===s?c.x1.webFetchRejected(t,"User rejected"):c.x1.webSearchRejected(t,"User rejected")}return"fetch"===s?c.x1.webFetchRejected(t,"Unknown response"):c.x1.webSearchRejected(t,"Unknown response")}catch(e){return(0,I.cY)(`web-${s}-permission-request-failed`,e),"fetch"===s?c.x1.webFetchRejected(t,e instanceof Error?e.message:"Permission request failed"):c.x1.webSearchRejected(t,e instanceof Error?e.message:"Permission request failed")}}}a()}catch(e){a(e)}}))}

CLI output and reasoning formats

Source: 9969.index.js (Agent CLI) · bytes 957901–958188 · SHA-256 f9c29c7f4129…

Minified Agent CLI webpack module ./src/utils/output-format.ts (287 characters), the code behind the CLI output and reasoning formats. Identifiers are minified; the exact shipped code is below.

Exact shipped text
"./src/utils/output-format.ts"(e,t,n){n.d(t,{nt:()=>s});const r=["text","json","stream-json"];function s(e){if(null==e)return"text";if(function(e){return"string"==typeof e&&r.includes(e)}(e))return e;const t=r.join(", ");throw new Error(`Invalid --output-format. Allowed values: ${t}`)}}

Thinking completed event schema (desktop)

Source: extensions/cursor-agent-exec/dist/main.js (desktop) · bytes 3683077–3683127 · SHA-256 45759cdac052…

Decoded from the shipped protobuf descriptor for ThinkingCompletedUpdate.

No. Field Type Label
1 thinking_duration_ms int32 —
Exact shipped text
ThinkingCompletedUpdate|1 thinking_duration_ms 5

Thinking completed event schema (Agent CLI)

Source: index.js (Agent CLI) · bytes 5713658–5713708 · SHA-256 45759cdac052…

Decoded from the shipped protobuf descriptor for ThinkingCompletedUpdate.

No. Field Type Label
1 thinking_duration_ms int32 —
Exact shipped text
ThinkingCompletedUpdate|1 thinking_duration_ms 5

Thinking delta event schema (desktop)

Source: extensions/cursor-agent-exec/dist/main.js (desktop) · bytes 3682678–3682729 · SHA-256 4087a245d348…

Decoded from the shipped protobuf descriptor for ThinkingDeltaUpdate; referenced types resolved through Cursor's own generated classes (agent.v1).

No. Field Type Label
1 text string —
2 thinking_style enum ThinkingStyle optional
Exact shipped text
ThinkingDeltaUpdate|1 text 9|2 thinking_style #0?

Thinking delta event schema (Agent CLI)

Source: index.js (Agent CLI) · bytes 5713269–5713320 · SHA-256 4087a245d348…

Decoded from the shipped protobuf descriptor for ThinkingDeltaUpdate; referenced types resolved through Cursor's own generated classes (agent.v1).

No. Field Type Label
1 text string —
2 thinking_style enum ThinkingStyle optional
Exact shipped text
ThinkingDeltaUpdate|1 text 9|2 thinking_style #0?

Turn token and reasoning usage schema (desktop)

Source: extensions/cursor-agent-exec/dist/main.js (desktop) · bytes 3685681–3685821 · SHA-256 bd96b181f0b6…

Decoded from the shipped protobuf descriptor for TurnEndedUpdate.

No. Field Type Label
1 input_tokens int64 optional
2 output_tokens int64 optional
3 cache_read_tokens int64 optional
4 cache_write_tokens int64 optional
5 reasoning_tokens int64 optional
6 ended_at_ms uint64 optional
Exact shipped text
TurnEndedUpdate|1 input_tokens 3?|2 output_tokens 3?|3 cache_read_tokens 3?|4 cache_write_tokens 3?|5 reasoning_tokens 3?|6 ended_at_ms 4?

Turn token and reasoning usage schema (Agent CLI)

Source: index.js (Agent CLI) · bytes 5716192–5716315 · SHA-256 8da82b0e289e…

Decoded from the shipped protobuf descriptor for TurnEndedUpdate.

No. Field Type Label
1 input_tokens int64 optional
2 output_tokens int64 optional
3 cache_read_tokens int64 optional
4 cache_write_tokens int64 optional
5 reasoning_tokens int64 optional
Exact shipped text
TurnEndedUpdate|1 input_tokens 3?|2 output_tokens 3?|3 cache_read_tokens 3?|4 cache_write_tokens 3?|5 reasoning_tokens 3?

Session storage

ACP session storage

Source: 3351.index.js (Agent CLI) · bytes 65–1438 · SHA-256 f729565479e1…

Minified Agent CLI webpack module ./src/acp/acp-storage.ts (1,373 characters), the code behind the ACP session storage. Identifiers are minified; the exact shipped code is below.

Exact shipped text
"./src/acp/acp-storage.ts"(e,t,s){s.d(t,{$n:()=>r,Dj:()=>f,Ki:()=>g,N0:()=>m,Qb:()=>l,gM:()=>d,ib:()=>u,oW:()=>h,xo:()=>p});var a=s("node:fs/promises"),n=s("node:path"),o=s("../cursor-config/dist/paths.js");const r=1,i="meta.json";function l(){return(0,n.join)((0,o.WI)(),"acp-sessions")}function c(e){return(0,n.join)(l(),e)}function d(e){return(0,n.join)(c(e),"store.db")}async function u(e){const t=c(e);return await(0,a.mkdir)(t,{recursive:!0}),t}function h(e){return(0,n.resolve)(e)}async function p(e){try{return function(e){let t;try{t=JSON.parse(e)}catch{return}if(!t||"object"!=typeof t)return;const s=t;if("string"!=typeof s.cwd||0===s.cwd.length)return;const a="string"==typeof s.title&&s.title.length>0?s.title:void 0;return{schemaVersion:r,cwd:s.cwd,...void 0!==a?{title:a}:{}}}(await(0,a.readFile)((0,n.join)(e,i),"utf8"))}catch{return}}async function g(e){return p(c(e))}async function m(e,t){await async function(e,t){if(!(0,n.isAbsolute)(t.cwd))throw new Error(`ACP session cwd must be absolute (got ${JSON.stringify(t.cwd)})`);await(0,a.mkdir)(e,{recursive:!0}),await(0,a.writeFile)((0,n.join)(e,i),function(e){const t={schemaVersion:r,cwd:e.cwd,...void 0!==e.title?{title:e.title}:{}};return JSON.stringify(t)}({...t,cwd:h(t.cwd)}),"utf8")}(c(e),t)}async function f(e,t){const s=await g(e);s&&s.title!==t&&await m(e,{schemaVersion:r,cwd:s.cwd,title:t})}}

CLI chat metadata schema

Source: 9969.index.js (Agent CLI) · bytes 771382–772660 · SHA-256 37710ac5b10c…

Minified Agent CLI webpack module ./src/state/chat-session-meta.ts (1,278 characters), the code behind the CLI chat metadata schema. Identifiers are minified; the exact shipped code is below.

Exact shipped text
"./src/state/chat-session-meta.ts"(e,t,n){n.d(t,{F4:()=>o,Nq:()=>i,uf:()=>c});var r=n("node:fs/promises"),s=n("node:path");const o=1,a="meta.json";async function i(e){try{return function(e){let t;try{t=JSON.parse(e)}catch{return}if(!t||"object"!=typeof t)return;const n=t,r="number"==typeof n.createdAtMs&&Number.isFinite(n.createdAtMs)?Math.floor(n.createdAtMs):void 0;if(void 0===r)return;const s="number"==typeof n.updatedAtMs&&Number.isFinite(n.updatedAtMs)?Math.floor(n.updatedAtMs):void 0,a=!0===n.hasConversation,i=!0===n.isSubagent,c="string"==typeof n.title&&n.title.length>0?n.title:void 0,l="string"==typeof n.cwd&&n.cwd.length>0?n.cwd:void 0;return{schemaVersion:o,createdAtMs:r,hasConversation:a,...i?{isSubagent:!0}:{},...void 0!==c?{title:c}:{},...void 0!==s?{updatedAtMs:s}:{},...void 0!==l?{cwd:l}:{}}}(await(0,r.readFile)((0,s.join)(e,a),"utf8"))}catch{return}}async function c(e,t){await(0,r.mkdir)(e,{recursive:!0}),await(0,r.writeFile)((0,s.join)(e,a),function(e){const t={schemaVersion:o,createdAtMs:e.createdAtMs,hasConversation:e.hasConversation,...void 0!==e.title?{title:e.title}:{},...void 0!==e.updatedAtMs?{updatedAtMs:e.updatedAtMs}:{},...!0===e.isSubagent?{isSubagent:!0}:{},...void 0!==e.cwd?{cwd:e.cwd}:{}};return JSON.stringify(t)}(t),"utf8")}}

CLI chat session sidecar

Source: 9969.index.js (Agent CLI) · bytes 772661–774890 · SHA-256 ea45b1169ac4…

Minified Agent CLI webpack module ./src/state/chat-session-sidecar.ts (2,229 characters), the code behind the CLI chat session sidecar. Identifiers are minified; the exact shipped code is below.

Exact shipped text
"./src/state/chat-session-sidecar.ts"(e,t,n){n.a(e,(async(e,r)=>{try{n.d(t,{DN:()=>w,IE:()=>k,RM:()=>b,TF:()=>y});var s=n("node:fs/promises"),o=n("node:path"),a=n("../agent-kv/dist/index.js"),i=n("../cursor-sdk-local-runtime/dist/run-store/sqlite-blob-store.js"),c=n("./src/debug.ts"),l=n("./src/utils/terminal-title.ts"),d=n("./src/state/chat-session-meta.ts"),u=e([l]),m=u.then?(await u)():u;l=m[0];const p="store.db";function h(e){const t="number"==typeof e?e:0;return t<=0||!Number.isFinite(t)?0:t<1e11?Math.floor(1e3*t):t>=1e14&&t<1e17?Math.floor(t/1e3):t>=1e17?Math.floor(t/1e6):Math.floor(t)}function g(e){return(0,l.iq)(e)?e.trim():void 0}function f(e){return Boolean(e&&e.length>0)}function b(e,t=Date.now(),n){const r=h(e.get("createdAt"));return{schemaVersion:d.F4,title:g(e.get("name")),createdAtMs:r>0?r:Date.now(),updatedAtMs:t,hasConversation:f(e.get("latestRootBlobId")),...void 0!==e.get("subagentInfo")?{isSubagent:!0}:{},...void 0!==n?{cwd:n}:{}}}function v(e,t){const n=h(e.getMetadata("createdAt"));return{schemaVersion:d.F4,title:g(e.getMetadata("name")),createdAtMs:n>0?n:Date.now(),updatedAtMs:Date.now(),hasConversation:f(e.getMetadata("latestRootBlobId")),...void 0!==e.getMetadata("subagentInfo")?{isSubagent:!0}:{},...void 0!==t?{cwd:t}:{}}}async function x(e,t,n){await(0,d.uf)(e,v(t,n))}async function w(e){const t=(0,o.join)(e,p);let n;try{let r=Date.now();try{r=Math.floor((await(0,s.stat)(t)).mtimeMs)}catch{}n=await i.M.initAndLoad(t);const o=b(n,r);return await(0,d.uf)(e,o),o}catch(t){return void(0,c.cY)("Failed to backfill CLI chat session meta sidecar",{sessionDir:e,error:t instanceof Error?t.message:String(t)})}finally{n&&await n.dispose().catch((()=>{}))}}function y(e){return e?.title??(0,a.sh)().name}function k(e,t,n){let r=n?.cwd;const s=()=>{x(e,t,r).catch((t=>{(0,c.cY)("Failed to persist CLI chat session meta sidecar",{sessionDir:e,error:t instanceof Error?t.message:String(t)})}))};(async()=>{const n=await(0,d.Nq)(e);if(r=n?.cwd??r,!n)return void s();const o=v(t,r);n.title===o.title&&n.createdAtMs===o.createdAtMs&&n.hasConversation===o.hasConversation&&n.cwd===o.cwd||s()})(),t.subscribeToMetadata("name",s),t.subscribeToMetadata("latestRootBlobId",s)}r()}catch(j){r(j)}}))}

CLI chat session storage

Source: 9577.index.js (Agent CLI) · bytes 59097–59442 · SHA-256 705dbba076e9…

Minified Agent CLI webpack module ./src/state/index.ts (345 characters), the code behind the CLI chat session storage. Identifiers are minified; the exact shipped code is below.

Exact shipped text
"./src/state/index.ts"(e,t,r){r.d(t,{mh:()=>a,r7:()=>d,wk:()=>i});var s=r("node:crypto"),n=r("node:path"),o=r("../cursor-config/dist/paths.js");function a(){return(0,n.join)((0,o.WI)(),"chats")}function i(e){const t=(0,n.resolve)(e),r=(0,s.createHash)("md5").update(t).digest("hex");return(0,n.join)(a(),r)}function d(){return i(process.cwd())}}

Persistent terminal session storage

Source: index.js (Agent CLI) · bytes 2557269–2585289 · SHA-256 32034bde01c1…

Minified Agent CLI webpack module ./src/persistence/persistent-session.ts (28,020 characters), the code behind the persistent terminal session storage. Identifiers are minified; the exact shipped code is below.

Exact shipped text
"./src/persistence/persistent-session.ts"(t,e,r){"use strict";r.d(e,{Dy:()=>dt,Ge:()=>ft,N9:()=>ut,_7:()=>W,eT:()=>S,hO:()=>lt,qg:()=>mt,rD:()=>yt,y1:()=>E});var n=r("node:child_process"),s=r("node:crypto"),i=r.n(s),a=r("node:fs"),o=r.n(a),c=r("node:os"),u=r.n(c),l=r("node:path"),d=r.n(l),m=r("./src/workspaces/workspace-config.ts");const p="--cursor-persist-restore",f="cursor-agent",h="/tmp",g=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/,A=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,b=/^[a-f0-9]{32}$/,y=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,_="\t",w=["#{session_name}","#{session_attached}","#{@cursor_managed}","#{@cursor_workspace_hash}","#{@cursor_session_version}","#{@cursor_chat_id}","#{pane_title}","#{session_path}"].join(_),C=["TMUX","TMUX_PANE","TERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLORTERM"],v="CURSOR_AGENT_PERSIST_SESSION";function E(t=process.env){const e=t[v];return void 0!==e&&g.test(e)}function S(t){return[`Chat ${t.chatId} is still running in persistent session ${t.sessionName}.`,`Attach from an interactive terminal with: agent persist attach ${t.sessionName}`,`Or stop it before a headless resume with: agent persist stop ${t.sessionName}`].join("\n")}function I(t){const e={};for(const[r,n]of Object.entries(t))void 0!==n&&(e[r]=n);return e}function B(){const t="function"==typeof process.getuid?process.getuid():"user";return d().join(h,`cursor-agent-persist-${t}`)}function k(t){o().mkdirSync(t,{recursive:!0,mode:448});const e=o().lstatSync(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error("Persistent-session state path is not a secure directory");if("function"==typeof process.getuid&&e.uid!==process.getuid())throw new Error("Persistent-session state directory has the wrong owner");return 63&e.mode&&o().chmodSync(t,448),t}function P(t,e){if(!b.test(t))throw new Error("Invalid persistent-session launch identifier");return d().join(k(e??B()),`${t}.json`)}function x(t,e){const r=P(t,e),n=o().lstatSync(r);if(!n.isFile()||n.isSymbolicLink())throw new Error("Persistent-session launch state is not a regular file");if("function"==typeof process.getuid&&n.uid!==process.getuid())throw new Error("Persistent-session launch state has the wrong owner");if(63&n.mode)throw new Error("Persistent-session launch state is not owner-only");const s=o().readFileSync(r,"utf8");let i;o().unlinkSync(r);try{i=JSON.parse(s)}catch{throw new Error("Persistent-session launch state is invalid JSON")}const a=function(t){if("object"!=typeof t||null===t||Array.isArray(t))return;if(!("version"in t)||1!==t.version)return;if(!("argv"in t)||!Array.isArray(t.argv)||!t.argv.every((t=>"string"==typeof t)))return;if(!("environment"in t)||!function(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)&&Object.values(t).every((t=>"string"==typeof t))}(t.environment))return;const e="cwd"in t?t.cwd:void 0;return void 0===e||"string"==typeof e&&d().isAbsolute(e)?{version:1,argv:t.argv,environment:t.environment,..."string"==typeof e?{cwd:e}:{}}:void 0}(i);if(void 0===a)throw new Error("Persistent-session launch state has an invalid shape");return a}function R(t){return t.environment.CURSOR_CLI&&"agent"===t.argv[0]?{prefix:["agent"],tokens:t.argv.slice(1)}:{prefix:[],tokens:[...t.argv]}}function J(t){const e=t.indexOf("--"),r=-1===e?t.length:e;for(let e=0;e<r;e+=1){const r=t[e];if("--resume"===r){const r=t[e+1];return void 0!==r&&y.test(r)?r:void 0}if(r?.startsWith("--resume=")){const t=r.slice(9);return y.test(t)?t:void 0}}}function T(t){const e=o().realpathSync(t);if(!o().statSync(e).isDirectory())throw new Error(`Workspace is not a directory: ${t}`);return e}function q(t){return`'${t.replace(/'/g,"'\\''")}'`}function j(t){const e=t.environment??process.env;return k(d().join(k(t.stateRoot??B()),"completions",U(e)))}function D(t,e){return K(t),d().join(j(e),`${t}.status`)}function Q(t,e={}){let r,n;try{r=D(t,e)}catch{return}try{n=o().lstatSync(r)}catch{return}if(!n.isFile()||n.isSymbolicLink()||"function"==typeof process.getuid&&n.uid!==process.getuid()||63&n.mode)return{version:1,kind:"invalid",exitCode:1};try{const[t,e="",n="",s=""]=o().readFileSync(r,"utf8").split("\n");if("1"!==t||"pane-died"!==s&&"stopped"!==s)return{version:1,kind:"invalid",exitCode:1};if(n.length>0){const t=function(t){if(/^[0-9]+$/.test(t)){const e=Number.parseInt(t,10);return e>0&&e<=127?128+e:void 0}const e=t.toUpperCase().startsWith("SIG")?t.toUpperCase():`SIG${t.toUpperCase()}`,r=u().constants.signals[e];return"number"==typeof r?128+r:void 0}(n);return void 0===t||"pane-died"!==s?{version:1,kind:"invalid",exitCode:1}:{version:1,kind:"signal",exitCode:t,signal:n,reason:s}}if(!/^[0-9]+$/.test(e))return{version:1,kind:"invalid",exitCode:1};const i=Number.parseInt(e,10);return i>=0&&i<=255?{version:1,kind:"exit",exitCode:i,reason:s}:{version:1,kind:"invalid",exitCode:1}}catch{return{version:1,kind:"invalid",exitCode:1}}}function N(t){const e=K(t.sessionName),r=`${e}:`,n=["umask 077",`status=${q(t.status)}`,`signal=${q(t.signal)}`];return"pane-died"===t.reason&&n.push(`if [ -z "$status" ] && [ -z "$signal" ]; then dead_message=$(${q(t.tmuxBinary)} capture-pane -p -t ${q(r)} -S -1 2>/dev/null); case "$dead_message" in *"Pane is dead (signal "*) signal=\${dead_message##*"Pane is dead (signal "}; signal=\${signal%%,*};; esac; fi`),n.push(`printf '1\\n%s\\n%s\\n%s\\n' "$status" "$signal" ${q(t.reason)} > ${q(t.temporaryFile)}`,"write_status=$?",`if [ "$write_status" -eq 0 ]; then ln ${q(t.temporaryFile)} ${q(t.completionFile)} 2>/dev/null; link_status=$?; rm -f -- ${q(t.temporaryFile)}; if [ "$link_status" -ne 0 ] && [ ! -f ${q(t.completionFile)} ]; then write_status=$link_status; fi; fi`),void 0!==t.bindingDirectory&&n.push(`chat_id=${q("#{@cursor_chat_id}")}`,`case "$chat_id" in ""|*[!0-9A-Fa-f-]*) ;; *) rm -f -- ${q(t.bindingDirectory)}/"$chat_id.json" ;; esac`),t.killSession&&n.push(`${q(t.tmuxBinary)} kill-session -t ${q(e)} >/dev/null 2>&1`),n.push('exit "$write_status"'),`run-shell ${q(n.join("; "))}`}function O(t){const e=t.CURSOR_AGENT_TMUX_PATH?.trim();if(e)return e;const r=t.AGENT_TMUX_ROOT_PATH?.trim();return r?d().join(r,"bin","tmux"):"tmux"}function M(t){const e={},r=["PATH","HOME","SHELL","USER","LOGNAME","LANG","TERM","COLORTERM"];for(const n of r)void 0!==t[n]&&(e[n]=t[n]);for(const[r,n]of Object.entries(t))r.startsWith("LC_")&&void 0!==n&&(e[r]=n);return e.TMUX_TMPDIR=h,e}function U(t){const e=t.CURSOR_AGENT_TMUX_SERVER_NAME?.trim();return void 0!==e&&A.test(e)?e:f}function L(t,e){return["-u","-L",U(e),"-f","/dev/null",...t]}function F(t){if(t.attached){const e=(0,n.spawnSync)(t.binary,L(t.commandArgs,t.environment),{env:M(t.environment),stdio:"inherit"});return{status:e.status,stdout:"",stderr:"",error:e.error}}const e=(0,n.spawnSync)(t.binary,L(t.commandArgs,t.environment),{encoding:"utf8",env:M(t.environment),timeout:t.timeout});return{status:e.status,stdout:e.stdout??"",stderr:e.stderr??"",error:e.error}}function $(t,e,r=!1,n=1e4){const s=e.environment??process.env;return(e.runner??F)({binary:O(s),commandArgs:t,environment:s,timeout:r?0:n,attached:r})}function G(t){return(t.stderr.trim()||t.error?.message||"unknown error").replace(/\s+/g," ").slice(0,500)}function K(t){if(!g.test(t))throw new Error(`Invalid persistent session name: ${t}`);return t}function H(t={}){const e=$(["list-sessions","-F",w],t);if(0===e.status)return function(t){const e=[];for(const r of t.split("\n")){if(0===r.trim().length)continue;const t=r.includes(_),n=r.split(t?_:"|");t||n.splice(6,0,"");const[s="",i="0",a="",o="",c="",u="",l="",...d]=n;"1"===a&&g.test(s)&&0!==o.length&&"1"===c&&e.push({name:s,attachedClientCount:Number.parseInt(i,10)||0,workspaceHash:o,version:c,chatId:u,taskTitle:z(l),workspacePath:d.join(t?_:"|")})}return e}(e.stdout);if(function(t){const e=`${t.stderr}\n${t.error?.message??""}`.toLowerCase();return e.includes("no server running")||e.includes("failed to connect to server")||e.includes("error connecting to")}(e))return[];throw new Error(`Could not list tmux sessions: ${G(e)}`)}function z(t){return Array.from(t,(t=>{const e=t.codePointAt(0)??0;return e<=31||127===e?" ":t})).join("").replace(/\s+/g," ").trim()}function W(t,e={}){if(!y.test(t))return{kind:"absent"};const r=t.toLowerCase();let n;try{n=at([t],e)}catch(t){return{kind:"unavailable",error:t instanceof Error?t.message:String(t)}}try{const n=H(e),s=et(t,n,e),i=n.find((t=>t.chatId.toLowerCase()===r));return void 0!==i?{kind:"found",session:i}:void 0!==s?{kind:"unavailable",error:`Chat ${t} is owned by persistent session ${s.session.name} on tmux server ${s.serverName}`}:{kind:"absent"}}catch(r){const n=X(t,e.stateRoot);return"absent"===n.kind?{kind:"absent"}:{kind:"unavailable",error:"unavailable"===n.kind?n.error:r instanceof Error?r.message:String(r)}}finally{for(const t of n.reverse())it(t)}}function Y(t){return k(d().join(k(t??B()),"bindings"))}function V(t,e){if(!y.test(t))throw new Error("Persistent-session chat ID must be a UUID");return d().join(Y(e),`${t.toLowerCase()}.json`)}function X(t,e){let r,n;try{r=V(t,e)}catch(t){return{kind:"unavailable",error:t instanceof Error?t.message:String(t)}}try{n=o().lstatSync(r)}catch(t){return"ENOENT"===t.code?{kind:"absent"}:{kind:"unavailable",error:`Could not inspect persistent chat binding ${r}: ${t instanceof Error?t.message:String(t)}`}}if(!n.isFile()||n.isSymbolicLink()||"function"==typeof process.getuid&&n.uid!==process.getuid()||63&n.mode)return{kind:"unavailable",error:`Persistent chat binding is not an owner-only regular file: ${r}`};try{const e=JSON.parse(o().readFileSync(r,"utf8"));return"object"==typeof e&&null!==e&&"version"in e&&1===e.version&&"chatId"in e&&"string"==typeof e.chatId&&e.chatId.toLowerCase()===t.toLowerCase()&&"sessionName"in e&&"string"==typeof e.sessionName&&g.test(e.sessionName)&&(!("serverName"in e)||"string"==typeof e.serverName&&A.test(e.serverName))?{kind:"found",binding:{version:1,chatId:e.chatId,sessionName:e.sessionName,..."serverName"in e&&"string"==typeof e.serverName?{serverName:e.serverName}:{}}}:{kind:"unavailable",error:`Persistent chat binding has invalid contents: ${r}`}}catch(t){return{kind:"unavailable",error:`Could not read persistent chat binding ${r}: ${t instanceof Error?t.message:String(t)}`}}}function Z(t){K(t.sessionName);const e=t.serverName??f;if(!A.test(e))throw new Error("Persistent-session tmux server name is invalid");const r=V(t.chatId,t.stateRoot),n=`${r}.${i().randomBytes(8).toString("hex")}`;o().writeFileSync(n,JSON.stringify({version:1,chatId:t.chatId,sessionName:t.sessionName,serverName:e}),{encoding:"utf8",flag:"wx",mode:384});try{o().renameSync(n,r)}catch(t){try{o().unlinkSync(n)}catch{}throw t}return r}function tt(t,e,r){const n=X(t,r);if("unavailable"===n.kind)throw new Error(n.error);if("absent"!==n.kind&&n.binding.sessionName===e)try{o().unlinkSync(V(t,r))}catch(t){if("ENOENT"!==t.code)throw t}}function et(t,e,r){const n=X(t,r.stateRoot);if("absent"===n.kind)return;if("unavailable"===n.kind)throw new Error(n.error);const s=n.binding,i=U(r.environment??process.env);if(void 0===s.serverName){const n=e.find((e=>e.name===s.sessionName&&e.chatId.toLowerCase()===t.toLowerCase()));if(void 0!==n)return{binding:s,session:n,serverName:i};if(i!==f){const e=H({...r,environment:{...r.environment??process.env,CURSOR_AGENT_TMUX_SERVER_NAME:f}}).find((e=>e.name===s.sessionName&&e.chatId.toLowerCase()===t.toLowerCase()));if(void 0!==e)return{binding:s,session:e,serverName:f}}throw new Error(`Legacy persistent chat binding cannot be safely attributed to a tmux server: ${V(t,r.stateRoot)}`)}const a=s.serverName,o=(a===i?e:H({...r,environment:{...r.environment??process.env,CURSOR_AGENT_TMUX_SERVER_NAME:a}})).find((e=>e.name===s.sessionName&&e.chatId.toLowerCase()===t.toLowerCase()));if(void 0!==o)return{binding:s,session:o,serverName:a};tt(t,s.sessionName,r.stateRoot)}const rt=new Set;function nt(t){if(!Number.isSafeInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(t){return"ESRCH"!==t.code}}function st(t,e){const r=d().join(function(t){return k(d().join(k(t.stateRoot??B()),"claim-locks"))}(e),`${t.toLowerCase()}.lock`);if(rt.has(r))throw new Error(`Persistent chat ownership is already changing for ${t}`);const n=i().randomBytes(16).toString("hex");for(;;){try{o().mkdirSync(r,{mode:448});try{o().writeFileSync(d().join(r,"owner.json"),JSON.stringify({version:1,pid:process.pid,token:n}),{encoding:"utf8",flag:"wx",mode:384})}catch(t){throw o().rmSync(r,{recursive:!0,force:!0}),t}return rt.add(r),{directory:r,token:n}}catch(t){if("EEXIST"!==t.code)throw new Error(`Could not lock persistent chat ownership: ${t instanceof Error?t.message:String(t)}`)}let e=!1;try{const t=o().lstatSync(r);let n;try{n=JSON.parse(o().readFileSync(d().join(r,"owner.json"),"utf8"))}catch{}const s="object"==typeof n&&null!==n&&"pid"in n&&"number"==typeof n.pid?n.pid:void 0;e=void 0===s?Date.now()-t.mtimeMs>1e3:!nt(s)}catch{continue}if(!e)throw new Error(`Persistent chat ownership is currently changing for ${t}`);{const t=`${r}.abandoned-${n}`;try{o().renameSync(r,t),o().rmSync(t,{recursive:!0,force:!0})}catch{}}}}function it(t){try{const e=JSON.parse(o().readFileSync(d().join(t.directory,"owner.json"),"utf8"));if("object"!=typeof e||null===e||!("token"in e)||e.token!==t.token)return;o().rmSync(t.directory,{recursive:!0,force:!0})}catch{}finally{rt.delete(t.directory)}}function at(t,e){const r=[];try{for(const n of[...new Set(t.map((t=>t.toLowerCase())))].sort())r.push(st(n,e));return r}catch(t){for(const t of r.reverse())it(t);throw t}}function ot(t,e){const r=(e.environment??process.env).TMUX_PANE;if(void 0===r||!/^%\d+$/.test(r))return!1;const n=$(["display-message","-p","-t",r,"#{session_name}|#{pane_pid}"],e);if(0!==n.status)throw new Error(`Could not verify persistent-session process identity: ${G(n)}`);const[s,i]=n.stdout.trim().split("|");return s===t&&Number(i)===process.pid}function ct(t,e,r){const n=$(["set-option","-t",K(t),"@cursor_chat_id",e],r);if(0!==n.status)throw new Error(`Could not bind tmux session to chat: ${G(n)}`)}function ut(t,e={}){if(!y.test(t))throw new Error("Persistent-session chat ID must be a UUID");const r=e.environment??process.env,n=r[v];if(void 0===n||!g.test(n))return;if(!ot(n,e))return;const s=at([t],e);try{const s=H(e),i=et(t,s,e),a=s.find((t=>t.name===n));if(void 0===a)return;const o=t.toLowerCase(),c=s.find((t=>t.name!==n&&t.chatId.toLowerCase()===o)),u=U(r),l=c??(void 0===i||i.serverName===u&&i.session.name===n?void 0:i.session);if(void 0!==l)throw new Error(`Chat ${t} is already running in persistent session ${l.name}`);if(a.chatId.length>0&&a.chatId.toLowerCase()!==o)throw new Error(`Persistent session ${n} is already bound to chat ${a.chatId}`);return ct(n,t,e),!0===e.writeBindingFile&&Z({chatId:t,sessionName:n,serverName:u,stateRoot:e.stateRoot}),{...a,chatId:t}}finally{for(const t of s.reverse())it(t)}}function lt(t,e={}){const{previousChatId:r,nextChatId:n}=t;if(!y.test(r)||!y.test(n))throw new Error("Persistent-session chat IDs must be UUIDs");const s=e.environment??process.env,i=s[v];if(void 0===i||!g.test(i)||!ot(i,e))return{rebind(){},rollback(){},release(){}};const a=at([r,n],e);let o=!1,c=!1;try{const t=H(e);et(r,t,e);const u=et(n,t,e),l=t.find((t=>t.name===i));if(void 0===l)throw new Error(`Persistent session not found: ${i}`);if(l.chatId.length>0&&l.chatId.toLowerCase()!==r.toLowerCase())throw new Error(`Persistent session ${i} is bound to chat ${l.chatId}, not ${r}`);const d=U(s),m=t.find((t=>t.name!==i&&t.chatId.toLowerCase()===n.toLowerCase()))??(void 0===u||u.serverName===d&&u.session.name===i?void 0:u.session);if(void 0!==m)throw new Error(`Chat ${n} is already running in persistent session ${m.name}`);const p=(t,r)=>{ct(i,r,e);try{Z({chatId:r,sessionName:i,serverName:d,stateRoot:e.stateRoot}),tt(t,i,e.stateRoot)}catch(n){throw ct(i,t,e),tt(r,i,e.stateRoot),n}};return{rebind(){o||c||(c=!0,p(r,n))},rollback(){!o&&c&&(p(n,r),c=!1)},release(){if(!o){o=!0;for(const t of a.reverse())it(t)}}}}catch(t){for(const t of a.reverse())it(t);throw t}}function dt(t,e,r={}){if(void 0===H(r).find((e=>e.name===t))){if(!0===r.allowMissingCompletion){const e=Q(t,r);if(void 0!==e)return e.exitCode}throw new Error(`Cursor-managed persistent session not found: ${t}`)}const n=K(t),s=["set-option","-t",n,"status","off",";","attach-session"];e&&s.push("-d"),s.push("-t",n);const i=$(s,r,!0);if(void 0!==i.error)throw new Error(`Failed to attach to ${t}: ${i.error.message}`);const a=Q(t,r);return void 0!==a?a.exitCode:0!==i.status?i.status??1:H(r).some((e=>e.name===t))?0:1}function mt(t={}){const e=t.environment??process.env,r=e[v];if(void 0===r||!g.test(r)||void 0===e.TMUX)throw new Error("/detach is only available inside a persistent session");const n=$(["detach-client","-s",K(r)],t);if(0!==n.status)throw new Error(`Could not detach persistent session: ${G(n)}`)}function pt(t){return"darwin"===t?"Install tmux with: brew install tmux":"Install tmux with: sudo apt-get install tmux (or use your Linux distribution's package manager)"}function ft(t=process.stdin.fd){const e=Buffer.alloc(128);let r=0;for(;0===r;)try{if(r=o().readSync(t,e,0,e.length,null),0===r)return!1}catch(t){if("object"==typeof t&&null!==t&&"code"in t&&"EAGAIN"===t.code){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25);continue}throw t}const n=e.toString("utf8",0,r).trim().toLowerCase();return"y"===n||"yes"===n}function ht(){return process.stderr.write("Continue without persistence? [y/N] "),ft()}function gt(t){return 0===$(["-V"],t).status}function At(t,e){if("darwin"!==e.platform&&"linux"!==e.platform)return e.writeStderr("Persistent tmux sessions are supported only on Linux and macOS.\n"),1;const r={environment:e.environment,runner:e.runner};if(!gt(r))return e.writeStderr(`Persistence requires tmux. ${pt(e.platform)}\n`),1;try{const n=H(r);if("list"===t.command)return 0===n.length?(e.writeStdout("No Cursor-managed persistent sessions.\n"),0):(e.writeStdout(function(t){const e=1===t.length?"session":"sessions",r=[`${t.length} persistent ${e}:`];for(const[e,n]of t.entries()){const s=n.attachedClientCount>0?`Attached (${n.attachedClientCount} client${1===n.attachedClientCount?"":"s"})`:"Detached (running in background)",i=z(n.taskTitle);r.push("",`Task: ${i||"Untitled"}`,`  Status: ${s}`,`  Session: ${n.name}`,`  Chat ID: ${n.chatId||"-"}`,`  Workspace: ${n.workspacePath}`,`  Attach: agent persist attach ${n.name}`),e===t.length-1&&r.push("")}return r.join("\n")}(n)),0);const s=t.sessionName;return void 0===s?1:"attach"===t.command?dt(s,!1,r):function(t,e={}){if(void 0===H(e).find((e=>e.name===t)))return!1;const r=e.environment??process.env,n=`${K(t)}:`,s=D(t,e);var a;return 0===$(["set-hook","-w","-t",n,"pane-died",(a={sessionName:t,completionFile:s,temporaryFile:`${s}.${i().randomBytes(8).toString("hex")}.tmp`,tmuxBinary:O(r),bindingDirectory:Y(e.stateRoot)},N({...a,status:"0",signal:"",reason:"stopped",killSession:!0})),";","run-shell","-t",n,'kill -HUP "#{pane_pid}"'],e).status}(s,r)?(e.writeStdout(`Stopped persistent session: ${s}\n`),0):(e.writeStderr(`Cursor-managed persistent session not found: ${s}\n`),1)}catch(t){return e.writeStderr(`Error: ${t instanceof Error?t.message:String(t)}\n`),1}}function bt(t,e){t.length=2,t.push(...e)}function yt(t={}){const e=t.argv??process.argv,r=t.environment??process.env,n=t.platform??"darwin",s=t.runner??F,a=t.writeStdout??(t=>process.stdout.write(t)),c=t.writeStderr??(t=>process.stderr.write(t)),u=function(t){if(3===t.argv.length&&t.argv[0]===p&&void 0!==t.argv[1]&&void 0!==t.argv[2]&&b.test(t.argv[1])&&g.test(t.argv[2]))return{kind:"restore",launchId:t.argv[1],sessionName:t.argv[2]};const{prefix:e,tokens:r}=R(t);if("persist"===r[0]){const t=r[1];if("--help"===t||"-h"===t)return{kind:"help"};if("list"===t)return 2===r.length?{kind:"manage",command:t,sessionName:void 0}:{kind:"invalid-management",message:"Usage: agent persist list"};if("attach"===t||"stop"===t){const e=r[2];return void 0===e||3!==r.length?{kind:"invalid-management",message:`Usage: agent persist ${t} <session>`}:{kind:"manage",command:t,sessionName:e}}const n=r.slice(1);return{kind:"launch",forwardedArgv:[...e,...n],resumeChatId:J(n)}}return{kind:"none"}}({argv:e.slice(2),environment:r});if("none"===u.kind)return;if("help"===u.kind)return a("Usage:\n  agent persist [options] [prompt...]\n  agent persist list\n  agent persist attach <session>\n  agent persist stop <session>\n\nStart or manage Cursor sessions that survive terminal and SSH disconnects.\n"),0;if("restore"===u.kind){!function(t){const e={};for(const r of C){const n=t.environment[r];void 0!==n&&(e[r]=n)}for(const e of Object.keys(t.environment))delete t.environment[e];Object.assign(t.environment,t.state.environment,e,{[v]:t.sessionName}),void 0!==t.state.cwd&&(t.changeDirectory??process.chdir)(t.state.cwd),t.argv.length=2,t.argv.push(...t.state.argv)}({state:x(u.launchId,t.stateRoot),argv:e,environment:r,sessionName:u.sessionName});const n=e=>{!function(t){const e=t.options??{};try{!function(t){if(!Number.isInteger(t.exitCode)||t.exitCode<0||t.exitCode>255)throw new Error("Persistent-session exit code must be an integer from 0 to 255");const e=D(t.sessionName,t.options??{}),r=`${e}.${i().randomBytes(8).toString("hex")}`;o().writeFileSync(r,function(t){return`1\n${t.status}\n${t.signal}\n${t.reason}\n`}({status:String(t.exitCode),signal:"",reason:t.reason}),{encoding:"utf8",flag:"wx",mode:384});try{o().linkSync(r,e)}catch(t){if("object"!=typeof t||null===t||!("code"in t)||"EEXIST"!==t.code)throw t}finally{try{o().unlinkSync(r)}catch{}}}({sessionName:t.sessionName,exitCode:t.exitCode,reason:"pane-died",options:e})}catch{}try{const r=U(e.environment??process.env);for(const n of o().readdirSync(Y(e.stateRoot))){const s=/^([0-9a-f-]+)\.json$/i.exec(n);if(!s)continue;const i=s[1],a=X(i,e.stateRoot);"found"===a.kind&&a.binding.sessionName===t.sessionName&&(a.binding.serverName??f)===r&&tt(i,t.sessionName,e.stateRoot)}}catch{}try{$(["kill-session","-t",K(t.sessionName)],e)}catch{}}({sessionName:u.sessionName,exitCode:e,options:{environment:r,runner:s,stateRoot:t.stateRoot}})};return void(t.registerProcessExit?t.registerProcessExit(n):process.once("exit",n))}if("invalid-management"===u.kind)return c(`${u.message}\n`),1;if("manage"===u.kind)return At(u,{environment:r,platform:n,runner:s,writeStdout:a,writeStderr:c});if(r.TMUX)return void bt(e,u.forwardedArgv);if("darwin"!==n&&"linux"!==n)return c("Persistent tmux sessions are supported only on Linux and macOS.\n"),1;const l={environment:r,runner:s},h=O(r);if(!gt(l))return c(`Persistence requires tmux. ${pt(n)}\n`),(t.stdinIsTTY??Boolean(process.stdin.isTTY))&&(t.stdoutIsTTY??Boolean(process.stdout.isTTY))?(t.promptToContinue??ht)()?(c("Continuing without persistence; persistence is disabled.\n"),void bt(e,u.forwardedArgv)):(c("Aborted because persistence is unavailable.\n"),1):(c("Cannot continue without persistence from a non-interactive terminal.\n"),1);if(!(t.stdinIsTTY??Boolean(process.stdin.isTTY))||!(t.stdoutIsTTY??Boolean(process.stdout.isTTY)))return c("Persistence requires an interactive Linux or macOS terminal.\n"),1;const A=e[1];if(void 0===A)return c("Could not determine the Cursor CLI entrypoint.\n"),1;let y,_;try{if(void 0!==u.resumeChatId){const t=W(u.resumeChatId,l);if("unavailable"===t.kind)throw new Error(`Could not verify the persistent session for chat ${u.resumeChatId}: ${t.error}`);if("found"===t.kind){const e=t.session;return c(`Reattaching to persistent session ${e.name} for chat ${u.resumeChatId}.\n`),dt(e.name,!1,{...l,allowMissingCompletion:!0})}}const e=function(t){const{tokens:e}=R(t),r=function(t){const e=t.indexOf("--"),r=-1===e?t.length:e;for(let e=0;e<r;e+=1){const r=t[e];if("--workspace"===r)return t[e+1];if(r?.startsWith("--workspace="))return r.slice(12)}}(e);if(void 0!==r){if(0===r.length)throw new Error("--workspace requires a path or saved workspace name");const e=(0,m.iB)(r);return T(e?.directories[0]??d().resolve(t.cwd,r))}const n=T(t.cwd);return T(function(t){let e=t;for(;;){if(o().existsSync(d().join(e,".git")))return e;const r=d().dirname(e);if(r===e)return t;e=r}}(n))}({argv:u.forwardedArgv,environment:r,cwd:t.cwd??process.cwd()}),n=function(t){const e=i().createHash("sha256").update(t).digest("hex").slice(0,10),r=d().basename(t).toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"workspace";return{slug:r,hash:e,sessionBase:`cursor-${r}-${e}`}}(e),s=H(l),a=function(t){const e=new Set(t.existingNames),r=t.randomSuffix??i().randomBytes(3).toString("hex");if(!/^[a-z0-9]{1,12}$/.test(r))throw new Error("Invalid persistent-session name suffix");for(let n=1;n<1e6;n+=1){const s=`${t.sessionBase}-${n}-${r}`;if(!e.has(s))return s}throw new Error("Too many persistent sessions for this workspace")}({sessionBase:n.sessionBase,existingNames:s.map((t=>t.name))});y=function(t){const e=i().randomBytes(16).toString("hex"),r=P(e,t.stateRoot),n={version:1,argv:[...t.argv],environment:I(t.environment??process.env),cwd:d().resolve(t.cwd??process.cwd())};return o().writeFileSync(r,JSON.stringify(n),{encoding:"utf8",flag:"wx",mode:384}),{launchId:e,filePath:r}}({argv:u.forwardedArgv,environment:r,cwd:t.cwd??process.cwd(),stateRoot:t.stateRoot});const f=[(w={executable:t.executable??process.execPath,execArgv:t.execArgv??process.execArgv,entrypoint:A,launchId:y.launchId,sessionName:a}).executable,...w.execArgv,w.entrypoint,p,w.launchId,w.sessionName].map(q).join(" "),g=`cursor-launch-${y.launchId}`,b=function(t,e){const r=j(e),n=Date.now()-6048e5;for(const t of o().readdirSync(r,{withFileTypes:!0})){if(!t.isFile()||!t.name.endsWith(".status"))continue;const e=d().join(r,t.name);try{o().statSync(e).mtimeMs<n&&o().unlinkSync(e)}catch{}}const s=D(t,e);try{o().unlinkSync(s)}catch{}return s}(a,l),v=function(t){return N({...t,status:"#{pane_dead_status}",signal:"#{pane_dead_signal}",reason:"pane-died",killSession:!0})}({sessionName:a,completionFile:b,temporaryFile:`${b}.${y.launchId}.tmp`,tmuxBinary:h,bindingDirectory:Y(l.stateRoot)});y.launcherPath=function(t){const e=k(t.stateRoot??B()),r=d().join(e,`${t.launchId}.sh`),n=["#!/bin/sh","set -eu",...Object.entries(t.environment).filter((([t,e])=>void 0!==e&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)&&!C.includes(t))).map((([t,e])=>`export ${t}=${q(e)}`)),`${q(t.tmuxBinary)} wait-for ${q(t.launchReadyChannel)}`,`rm -f -- ${q(r)}`,`exec ${t.childCommand}`,""].join("\n");return o().writeFileSync(r,n,{encoding:"utf8",flag:"wx",mode:448}),r}({launchId:y.launchId,environment:r,childCommand:f,tmuxBinary:h,launchReadyChannel:g,stateRoot:t.stateRoot});const E=["/bin/sh",y.launcherPath].map(q).join(" "),S=[t.executable??process.execPath,"-e","setInterval(() => {}, 2147483647)"].map(q).join(" ");return _=a,function(t){const e=$(function(t){const e=K(t.sessionName),r=`${e}:`;return["new-session","-d","-s",t.sessionName,"-c",t.workspacePath,t.holderCommand,";","set-option","-t",e,"destroy-unattached","off",";","set-option","-t",e,"status","off",";","set-option","-t",e,"@cursor_managed","1",";","set-option","-t",e,"@cursor_workspace_hash",t.workspaceHash,";","set-option","-t",e,"@cursor_session_version","1",";","set-option","-t",e,"@cursor_chat_id","",";","set-option","-w","-t",r,"remain-on-exit","on",";","respawn-pane","-k","-t",r,t.childCommand,";","set-hook","-w","-t",r,"pane-died",t.paneDiedHook,";","wait-for","-S",t.launchReadyChannel]}(t),t.options,!1,3e4);if(0!==e.status)throw new Error(`Could not create tmux session ${t.sessionName}: ${G(e)}`)}({sessionName:a,workspacePath:e,workspaceHash:n.hash,holderCommand:S,childCommand:E,paneDiedHook:v,launchReadyChannel:g,options:l}),c(`Started persistent session ${a}. Use /detach to leave it running; reconnect with agent persist list.\n`),dt(a,!1,{...l,allowMissingCompletion:!0})}catch(t){if(void 0!==_&&$(["kill-session","-t",K(_)],l),void 0!==y)for(const t of[y.filePath,y.launcherPath])if(void 0!==t)try{o().unlinkSync(t)}catch{}return c(`Error: ${t instanceof Error?t.message:String(t)}\n`),1}var w}}

CLI worktree storage

Source: index.js (Agent CLI) · bytes 2597083–2599355 · SHA-256 ba3e30d443bb…

Minified Agent CLI webpack module ./src/project/worktree.ts (2,272 characters), the code behind the CLI worktree storage. Identifiers are minified; the exact shipped code is below.

Exact shipped text
"./src/project/worktree.ts"(t,e,r){"use strict";r.a(t,(async(t,n)=>{try{r.d(e,{FI:()=>C,Tb:()=>w});var s=r("node:fs/promises"),i=r("node:os"),a=r("node:path"),o=r.n(a),c=r("../git-core/dist/git-exec.js"),u=r("./src/debug.ts"),l=r("./src/mcp/approval.tsx"),d=r("./src/utils/git.ts"),m=r("./src/workspace/approval.tsx"),p=r("./src/project/worktree-name-mode.ts"),f=t([l,m]);[l,m]=f.then?(await f)():f;const h=/^[A-Za-z0-9._-]+$/;function g(){return process.env.CURSOR_WORKTREES_ROOT??o().join((0,i.homedir)(),".cursor","worktrees")}function A(t){const e=t.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"worktree"}async function b(t){const e=await(0,d.dj)(["rev-parse","--abbrev-ref","HEAD"],t),r=e&&"HEAD"!==e?e:o().basename(t),n=crypto.randomUUID().replace(/-/g,"").slice(0,3);return`${A(r)}-${n}`}async function y(t){try{return await(0,s.stat)(t),!0}catch{return!1}}async function _(t,e){try{await(0,m.nF)({sourceWorkspace:t,targetWorkspace:e})}catch(t){(0,u.W6)("Failed to inherit workspace trust:",t instanceof Error?t.message:String(t),"WARN")}}async function w(t,e){const{worktree:r,base:n}=e,i=await(0,d.F4)(["rev-parse","--show-toplevel"],t,`Unable to resolve git repository from "${t}"`),a=(0,p.t)(r),u=a.length>0?a:await b(i);if(!h.test(u))throw new Error(`Invalid --worktree name "${u}". Use only letters, numbers, ".", "_", or "-".`);const m=A(o().basename(i)),f=o().join(g(),m,u);if(await y(f)){if(!(await(0,s.stat)(f)).isDirectory())throw new Error(`Worktree path exists and is not a directory: ${f}`);if(!await y(o().join(f,".git")))throw new Error(`Directory exists but is not a git worktree: ${f}. Please remove or rename it.`);return await _(t,f),await(0,l.J9)(t,f),f}await(0,s.mkdir)(o().dirname(f),{recursive:!0});const w=n?["worktree","add","-b",u,f,n]:["worktree","add","-b",u,f];try{await(0,c.uM)("git",w,{cwd:i,encoding:"utf8",maxBuffer:1048576})}catch{await(0,d.F4)(["worktree","add",f,u],i,`Failed to create worktree "${u}"`)}return await _(t,f),await(0,l.J9)(t,f),f}function C(){const t=process.cwd(),e=g(),r=o().relative(e,t);if(r.startsWith("..")||o().isAbsolute(r))return null;const n=r.split(o().sep).filter(Boolean);return n.length>=2?n[n.length-1]??null:null}n()}catch(v){n(v)}}))}

Composer storage key

Source: out/vs/workbench/workbench.desktop.main.js (desktop) · bytes 495059–495082 · SHA-256 dfecd690cb65…

composer.composerData

Daemon session persistence

Source: extensions/cursor-agent-host/dist/agent-host-daemon/dist/bin/daemon.cjs (desktop) · bytes 26489892–26503781 · SHA-256 8946c0c41eff…

Unminified desktop source for src/session-persistence.ts (13,889 characters), the code behind the daemon session persistence. It reads as shipped, below.

Exact shipped text
// src/session-persistence.ts
function createDaemonSessionPersistence(sessionStorage, sessionExecRegistry) {
  const { registry: registry2, records: records2 } = sessionStorage;
  const createSessionStore = (args) => {
    const store = registry2.consumePreparedSessionStore(
      args.sessionId
    );
    return store === void 0 ? void 0 : withRegistryHeldForks(store, args.sessionId);
  };
  const explicitForkSources = /* @__PURE__ */ new Map();
  const pendingForks = /* @__PURE__ */ new Map();
  let hasLiveSession = (_sessionId) => false;
  const withRegistryHeldForks = (store, sessionId) => ({
    getConversationState: () => store.getConversationState(),
    handleCheckpoint: (ctx, checkpoint) => store.handleCheckpoint(ctx, checkpoint),
    getBlobStore: () => store.getBlobStore(),
    markLive: () => {
      pendingForks.delete(sessionId);
      store.markLive?.();
    },
    dispose: () => {
      if (pendingForks.delete(sessionId)) {
        try {
          const parent = sessionExecRegistry.peekOrPersistedExecConfig(sessionId)?.parent;
          if (parent !== void 0) {
            records2.deleteSubagentChildSessionId({
              parentSessionId: parent.parentSessionId,
              parentToolCallId: parent.parentToolCallId,
              childSessionId: sessionId
            });
          }
          records2.deleteSessionExecConfig(sessionId);
          sessionExecRegistry.forget(sessionId);
        } finally {
          registry2.cleanupFailedSessionCreate(sessionId);
        }
        return;
      }
      return store.dispose?.();
    },
    createFork: async (ctx, args) => {
      assertPathSafeSessionId(args.sessionId);
      const explicit = explicitForkSources.get(ctx) === sessionId;
      const parentBlobs = store.getBlobStore();
      const ownership = sessionStorage.acquireSessionCreate(args.sessionId);
      if (ownership === void 0) {
        throw new Error(
          `session ${args.sessionId} has a pending delete; retry after startup reconciliation`
        );
      }
      let prepared;
      let forkExec;
      try {
        if (explicit) {
          sessionExecRegistry.inheritFromSession({
            destinationSessionId: args.sessionId,
            sourceSessionId: sessionId
          });
          forkExec = sessionExecRegistry.peekExecConfig(args.sessionId);
        }
        prepared = await registry2.prepareSession({
          sessionId: args.sessionId,
          allowCreate: true,
          initialHistory: (args.initialHistory ?? store.getConversationState()).toBinary(),
          legacyGetBlob: (blobId) => parentBlobs.getBlob(ctx, blobId),
          ...forkExec === void 0 ? {} : { workspacePaths: forkExec.workspacePaths },
          ctx
        });
      } finally {
        ownership.dispose();
      }
      const forkStore = prepared === void 0 ? void 0 : registry2.consumePreparedSessionStore(args.sessionId);
      if (forkStore === void 0) {
        if (explicit) {
          records2.deleteSessionExecConfig(args.sessionId);
          sessionExecRegistry.forget(args.sessionId);
        }
        throw new Error(`host-owned storage could not be seeded for fork ${args.sessionId}`);
      }
      pendingForks.set(args.sessionId, ctx);
      return withRegistryHeldForks(forkStore, args.sessionId);
    }
  });
  const sessionTurns = /* @__PURE__ */ new Map();
  const inSessionTurn = async (sessionId, run) => {
    const prior = sessionTurns.get(sessionId) ?? Promise.resolve();
    const turn = prior.then(run, run);
    sessionTurns.set(sessionId, turn);
    try {
      return await turn;
    } finally {
      if (sessionTurns.get(sessionId) === turn) {
        sessionTurns.delete(sessionId);
      }
    }
  };
  const prepareSession = async (args) => {
    assertPathSafeSessionId(args.sessionId);
    const ownership = args.allowCreate === true ? sessionStorage.acquireSessionCreate(args.sessionId) : void 0;
    if (args.allowCreate && ownership === void 0) {
      throw new Error(
        `session ${args.sessionId} has a pending delete; retry after startup reconciliation`
      );
    }
    let prepared;
    try {
      prepared = await registry2.prepareSession({
        sessionId: args.sessionId,
        allowCreate: args.allowCreate,
        ...args.workspacePaths === void 0 ? {} : { workspacePaths: args.workspacePaths },
        ...args.ctx === void 0 ? {} : { ctx: args.ctx }
      });
    } finally {
      ownership?.dispose();
    }
    if (prepared === void 0 && args.allowCreate) {
      throw new Error(`host-owned storage could not be seeded for session ${args.sessionId}`);
    }
    return prepared;
  };
  let hydrateSession;
  const withExecMetadata = (entry) => {
    const exec2 = sessionExecRegistry.peekOrPersistedExecConfig(
      entry.sessionId
    );
    if (exec2 === void 0) {
      return entry;
    }
    return {
      ...entry,
      workspace: { workspacePaths: exec2.workspacePaths },
      ...exec2.owningClientInstanceId === void 0 ? {} : { owningClientInstanceId: exec2.owningClientInstanceId },
      ...exec2.parent === void 0 ? {} : { parent: exec2.parent }
    };
  };
  const sessionCatalog = {
    async listSessions(ctx, request3, matches) {
      return registry2.listNativeCatalogEntries(
        request3?.limit ?? AGENT_HOST_SESSION_LIST_MAX_LIMIT,
        ctx,
        matches === void 0 ? void 0 : (entry) => {
          const catalogEntry = withExecMetadata(entry);
          return matches(catalogEntry) ? catalogEntry : void 0;
        }
      ).map(withExecMetadata);
    },
    async ensureLoaded(ctx, sessionId) {
      if (hydrateSession === void 0) {
        throw new Error("agent host is not ready");
      }
      return hydrateSession(ctx, sessionId);
    },
    async setTitle(_ctx, sessionId, title) {
      registry2.noteTitleChanged(sessionId, title);
    }
  };
  return {
    createSessionStore,
    sessionCatalog,
    async findExistingSubagentSessionId({
      parentSessionId,
      parentToolCallId
    }) {
      const childSessionId = records2.readSubagentChildSessionId({
        parentSessionId,
        parentToolCallId
      });
      if (childSessionId === void 0) {
        return void 0;
      }
      return inSessionTurn(childSessionId, async () => {
        if (!sessionStorage.hasDurableSession(childSessionId)) {
          return void 0;
        }
        return childSessionId;
      });
    },
    wrapHost(host, hooks) {
      hasLiveSession = (sessionId) => host.hasLiveSession?.(sessionId) ?? false;
      hydrateSession = wrapHostCreateSession(
        host,
        prepareSession,
        inSessionTurn,
        sessionStorage,
        sessionExecRegistry,
        hasLiveSession
      );
      wrapHostForkSession(host, pendingForks, explicitForkSources);
      wrapHostDeleteSession(
        host,
        inSessionTurn,
        sessionStorage,
        sessionExecRegistry,
        hooks?.onSessionForgotten
      );
    }
  };
}
function wrapHostCreateSession(host, prepareSession, inSessionTurn, sessionStorage, sessionExecRegistry, hasLiveSession) {
  const { registry: registry2, records: records2 } = sessionStorage;
  const originalCreateSession = host.createSession.bind(host);
  const createPrepared = async (ctx, request3, options2, prepared, cleanupOnFailure) => {
    const { initialHistory, ...withoutHistory } = request3;
    const forwarded = initialHistory !== void 0 && prepared.store.getConversationState().toBinary().byteLength > 0 ? withoutHistory : request3;
    let response;
    try {
      response = await originalCreateSession(ctx, forwarded, options2);
    } catch (error3) {
      if (isErrorWithMessage(error3, SESSION_ALREADY_EXISTS_SNIPPET)) {
        registry2.rollbackDanglingPreparedSession(request3.sessionId);
      } else if (cleanupOnFailure) {
        const live = hasLiveSession(request3.sessionId);
        if (live) {
          records2.reportPostKernelMetadataPersistenceFailure();
        } else {
          registry2.cleanupFailedSessionCreate(request3.sessionId);
        }
      }
      throw error3;
    }
    const parent = options2?.parent;
    if (parent !== void 0 && parent.parentSessionId.length > 0 && parent.parentToolCallId.length > 0) {
      records2.writeSubagentChildSessionId({
        parentSessionId: parent.parentSessionId,
        parentToolCallId: parent.parentToolCallId,
        childSessionId: request3.sessionId
      });
      sessionExecRegistry.stampParent(request3.sessionId, parent);
    }
    return response;
  };
  host.createSession = (ctx, request3, options2) => inSessionTurn(request3.sessionId, async () => {
    const cleanupOnFailure = !registry2.hasPreparedSession(request3.sessionId);
    const prepared = await prepareSession({
      sessionId: request3.sessionId,
      allowCreate: true,
      ...request3.sessionOptions?.workspacePaths === void 0 ? {} : { workspacePaths: request3.sessionOptions.workspacePaths },
      ctx
    });
    if (prepared === void 0) {
      throw new Error(`host-owned storage could not be seeded for session ${request3.sessionId}`);
    }
    return createPrepared(ctx, request3, options2, prepared, cleanupOnFailure);
  });
  return (ctx, sessionId) => inSessionTurn(sessionId, async () => {
    if (hasLiveSession(sessionId)) {
      return true;
    }
    const persistedExec = records2.readSessionExecConfig(sessionId);
    const cleanupOnFailure = !registry2.hasPreparedSession(sessionId);
    const prepared = await prepareSession({
      sessionId,
      allowCreate: false,
      ctx
    });
    if (prepared === void 0) {
      return false;
    }
    const nativeEntry = registry2.getNativeCatalogEntry(sessionId);
    let request3 = {
      sessionId
    };
    if (persistedExec === void 0) {
      const workspacePaths = nativeEntry?.workspace?.workspacePaths;
      if (workspacePaths === void 0) {
        registry2.rollbackDanglingPreparedSession(sessionId);
        return false;
      }
      request3 = {
        sessionId,
        sessionOptions: { workspacePaths: [...workspacePaths] }
      };
    }
    try {
      await createPrepared(
        ctx,
        request3,
        persistedExec?.parent === void 0 ? void 0 : { parent: persistedExec.parent },
        prepared,
        cleanupOnFailure
      );
    } catch (error3) {
      if (!isErrorWithMessage(error3, SESSION_ALREADY_EXISTS_SNIPPET)) {
        throw error3;
      }
      if (!hasLiveSession(sessionId)) {
        return false;
      }
    }
    const title = nativeEntry?.title;
    if (title !== void 0 && typeof host.setSessionTitle === "function") {
      await host.setSessionTitle(ctx, { sessionId, title });
    }
    return true;
  });
}
function wrapHostForkSession(host, pendingForks, explicitForkSources) {
  const originalForkSession = host.forkSession?.bind(host);
  if (originalForkSession === void 0) {
    return;
  }
  host.forkSession = async (ctx, request3) => {
    explicitForkSources.set(ctx, request3.sessionId);
    try {
      return await originalForkSession(ctx, request3);
    } finally {
      if (explicitForkSources.get(ctx) === request3.sessionId) {
        explicitForkSources.delete(ctx);
      }
      for (const [forkSessionId, forkCtx] of pendingForks) {
        if (forkCtx === ctx) {
          pendingForks.delete(forkSessionId);
        }
      }
    }
  };
}
function wrapHostDeleteSession(host, inSessionTurn, sessionStorage, sessionExecRegistry, onSessionForgotten) {
  const { registry: registry2, records: records2 } = sessionStorage;
  const originalDeleteSession = host.deleteSession.bind(host);
  const forgetDurableSession = (sessionId) => {
    records2.markSessionDeletePending(sessionId);
    if (!registry2.deleteSessionStorage(sessionId)) {
      records2.reportDeletePending("storage_delete_failed");
      throw new Error(`failed to delete host-owned storage for session ${sessionId}`);
    }
    try {
      records2.finishSessionDeleteRecords(sessionId);
    } catch (error3) {
      records2.reportDeletePending("metadata_cleanup_failed");
      throw error3;
    }
    sessionExecRegistry.forget(sessionId);
    onSessionForgotten?.(sessionId);
  };
  const forgetTree = async (ctx, sessionId, forgotten) => {
    const descendants = sessionExecRegistry.listDescendantSessionIds(sessionId);
    forgotten.add(sessionId);
    for (const childId of descendants) {
      if (forgotten.has(childId)) {
        continue;
      }
      await inSessionTurn(childId, async () => {
        try {
          await originalDeleteSession(ctx, { sessionId: childId });
        } catch (error3) {
          if (!isErrorWithMessage(error3, SESSION_NOT_FOUND_SNIPPET)) {
            throw error3;
          }
        }
        await forgetTree(ctx, childId, forgotten);
      });
    }
    forgetDurableSession(sessionId);
  };
  const deleteWithDescendants = async (ctx, request3) => {
    let response;
    try {
      response = await originalDeleteSession(ctx, request3);
    } catch (error3) {
      if (!(isErrorWithMessage(error3, SESSION_NOT_FOUND_SNIPPET) && (sessionStorage.hasDurableSession(request3.sessionId) || records2.hasSessionDeletePending(request3.sessionId)))) {
        throw error3;
      }
      response = {};
    }
    await forgetTree(ctx, request3.sessionId, /* @__PURE__ */ new Set());
    return response;
  };
  host.deleteSession = (ctx, request3) => inSessionTurn(request3.sessionId, () => deleteWithDescendants(ctx, request3));
}
function isErrorWithMessage(error3, snippet2) {
  return error3 instanceof Error && error3.message.includes(snippet2);
}
var SESSION_ALREADY_EXISTS_SNIPPET, SESSION_NOT_FOUND_SNIPPET;
var init_session_persistence = __esm({
  "src/session-persistence.ts"() {
    "use strict";
    init_runtime();
    init_storage();
    SESSION_ALREADY_EXISTS_SNIPPET = "Agent host session already exists:";
    SESSION_NOT_FOUND_SNIPPET = "Agent host session not found:";
  }
});

Daemon session storage

Source: extensions/cursor-agent-host/dist/agent-host-daemon/dist/bin/daemon.cjs (desktop) · bytes 26154160–26174181 · SHA-256 35a5c5a94bf8…

Unminified desktop source for src/session-storage.ts (20,021 characters), the code behind the daemon session storage. It reads as shipped, below.

Exact shipped text
// src/session-storage.ts
function resolveDaemonStorageDir(options2) {
  if (options2.storageDir !== void 0 && options2.storageDir.length > 0) {
    return options2.storageDir;
  }
  const fromEnv = (options2.env ?? process.env)[AGENT_HOST_DAEMON_BLOBS_DIR_ENV];
  return fromEnv !== void 0 && fromEnv.length > 0 ? fromEnv : options2.agentsDir;
}
function createDaemonSessionStorage(options2) {
  const storage = createHostStorage2({
    storageDir: options2.storageDir
  });
  if (storage === void 0) {
    throw new Error("agent-host-daemon storage requires a storage dir");
  }
  const globalStore = storage.openGlobalStore();
  const log5 = options2.log ?? stderrHostStorageLogger;
  const clock = options2.clock ?? realClock;
  let registry2;
  const records2 = new DaemonSessionRecords(
    globalStore,
    {
      hasNativeSession: (sessionId) => registry2?.hasNativeSession(sessionId) ?? false
    },
    log5
  );
  records2.reportDeletePending("backlog");
  reconcileDaemonSessionStorage(storage, records2, log5, clock.now());
  try {
    registry2 = new HostSessionRegistry({
      storage,
      log: log5,
      clock
    });
  } catch (error3) {
    globalStore.close();
    throw error3;
  }
  if ((0, import_node_fs40.existsSync)((0, import_node_path94.join)(options2.storageDir, "blobs.sqlite"))) {
    log5.warn(
      `[hostStorage] ${(0, import_node_path94.join)(options2.storageDir, "blobs.sqlite")} is from an earlier daemon and is not read; the sessions it holds do not list`
    );
  }
  return {
    storageDir: options2.storageDir,
    storage,
    registry: registry2,
    records: records2,
    acquireSessionCreate: (sessionId) => {
      if (!records2.tryAcquireSessionCreate(sessionId, process.pid)) {
        return void 0;
      }
      let disposed = false;
      return {
        dispose: () => {
          if (!disposed) {
            disposed = true;
            records2.releaseSessionCreate(sessionId, process.pid);
          }
        }
      };
    },
    // Older Task children may still resolve blobs through their parent store.
    blobStoreFor: (args) => {
      const parent = args.parentSessionId === void 0 ? records2.readSessionExecConfigLenient(args.sessionId)?.parent : void 0;
      return registry2.getPreparedBlobStore(
        parent === void 0 ? args : {
          sessionId: args.sessionId,
          rootSessionId: parent.rootSessionId,
          parentSessionId: parent.parentSessionId
        }
      );
    },
    hasDurableSession: (sessionId) => records2.hasSession(sessionId),
    close: () => {
      try {
        registry2.dispose();
      } finally {
        globalStore.close();
      }
    }
  };
}
function isOrphanReclaimMarker(value) {
  return typeof value === "object" && value !== null && "kind" in value && value.kind === "orphan-reclaim" && "token" in value && typeof value.token === "string";
}
function sessionDeletePendingKey(sessionId) {
  return `${SESSION_DELETE_PENDING_KEY_PREFIX}${sessionId}`;
}
function sessionCreateOwnerKeyPrefix(sessionId) {
  return `${SESSION_CREATE_OWNER_KEY_PREFIX}${sessionId}:`;
}
function sessionCreateOwnerKey(sessionId, pid) {
  return `${sessionCreateOwnerKeyPrefix(sessionId)}${pid}`;
}
function subagentChildKey(args) {
  return `${SUBAGENT_CHILD_KEY_PREFIX}${args.parentSessionId}:${args.parentToolCallId}`;
}
function subagentInvocationKey(args) {
  return `${SUBAGENT_INVOCATION_KEY_PREFIX}${args.parentSessionId}:${args.rootSessionId}:${args.parentToolCallId}`;
}
function parseSubagentInvocationKey(key, record3) {
  const rest = key.slice(SUBAGENT_INVOCATION_KEY_PREFIX.length);
  const parentEnd = rest.indexOf(":");
  const rootEnd = rest.indexOf(":", parentEnd + 1);
  if (parentEnd <= 0 || rootEnd <= parentEnd + 1) {
    return void 0;
  }
  return {
    parentSessionId: rest.slice(0, parentEnd),
    rootSessionId: rest.slice(parentEnd + 1, rootEnd),
    parentToolCallId: rest.slice(rootEnd + 1),
    record: record3
  };
}
function encodeSessionExecConfig(config2) {
  return {
    workspacePaths: [...config2.workspacePaths],
    projectDir: config2.projectDir,
    ...config2.owningClientInstanceId !== void 0 && config2.owningClientInstanceId.length > 0 ? { owningClientInstanceId: config2.owningClientInstanceId } : {},
    ...config2.isGlassRoot === true ? { isGlassRoot: true } : {},
    ...config2.interactionPolicy === void 0 ? {} : { interactionPolicy: config2.interactionPolicy },
    ...config2.localSubagentLimitsMaxRunning === void 0 ? {} : {
      localSubagentLimitsMaxRunning: config2.localSubagentLimitsMaxRunning
    },
    ...config2.hostedMcpRoutingEnabled === true ? { hostedMcpRoutingEnabled: true } : {},
    ...config2.hostedMcpLocalGrantIdentifiers === void 0 || config2.hostedMcpLocalGrantIdentifiers.length === 0 ? {} : {
      hostedMcpLocalGrantIdentifiers: [...config2.hostedMcpLocalGrantIdentifiers]
    },
    ...config2.parent === void 0 ? {} : {
      parent: {
        parentSessionId: config2.parent.parentSessionId,
        parentToolCallId: config2.parent.parentToolCallId,
        rootSessionId: config2.parent.rootSessionId
      }
    }
  };
}
function decodeSessionExecConfig(parsed) {
  if (typeof parsed !== "object" || parsed === null) {
    throw new Error("invalid persisted session exec config");
  }
  const record3 = parsed;
  const workspacePaths = record3.workspacePaths;
  const projectDir = record3.projectDir;
  if (!Array.isArray(workspacePaths) || workspacePaths.some((path53) => typeof path53 !== "string") || typeof projectDir !== "string") {
    throw new Error("invalid persisted session exec config");
  }
  const owningClientInstanceId = record3.owningClientInstanceId;
  const isGlassRoot = record3.isGlassRoot === true;
  if (workspacePaths.length === 0 && !isGlassRoot) {
    throw new Error("invalid persisted session exec config");
  }
  const interactionPolicy = record3.interactionPolicy;
  const localSubagentLimitsMaxRunning = record3.localSubagentLimitsMaxRunning;
  const hostedMcpLocalGrantIdentifiers = record3.hostedMcpLocalGrantIdentifiers;
  const grantIdentifiers = Array.isArray(hostedMcpLocalGrantIdentifiers) ? hostedMcpLocalGrantIdentifiers.filter(
    (value) => typeof value === "string" && value.length > 0
  ) : [];
  const parent = persistedSessionParent(record3.parent);
  return {
    workspacePaths: workspacePaths.map((path53) => (0, import_node_path94.resolve)(path53)),
    projectDir: (0, import_node_path94.resolve)(projectDir),
    ...typeof owningClientInstanceId === "string" && owningClientInstanceId.length > 0 ? { owningClientInstanceId } : {},
    ...isGlassRoot ? { isGlassRoot: true } : {},
    ...typeof interactionPolicy === "number" ? { interactionPolicy } : {},
    ...typeof localSubagentLimitsMaxRunning === "number" ? { localSubagentLimitsMaxRunning } : {},
    ...record3.hostedMcpRoutingEnabled === true ? { hostedMcpRoutingEnabled: true } : {},
    ...grantIdentifiers.length === 0 ? {} : { hostedMcpLocalGrantIdentifiers: grantIdentifiers },
    ...parent === void 0 ? {} : { parent }
  };
}
function sessionExecConfigsEqual(left, right) {
  return JSON.stringify(encodeSessionExecConfig(left)) === JSON.stringify(encodeSessionExecConfig(right));
}
function persistedSessionParent(value) {
  if (typeof value !== "object" || value === null) {
    return void 0;
  }
  if (!("parentSessionId" in value) || !("parentToolCallId" in value) || !("rootSessionId" in value)) {
    return void 0;
  }
  const parentSessionId = value.parentSessionId;
  const parentToolCallId = value.parentToolCallId;
  const rootSessionId = value.rootSessionId;
  if (typeof parentSessionId !== "string" || parentSessionId.length === 0 || typeof parentToolCallId !== "string" || parentToolCallId.length === 0 || typeof rootSessionId !== "string" || rootSessionId.length === 0) {
    return void 0;
  }
  return {
    parentSessionId,
    parentToolCallId,
    rootSessionId
  };
}
function refuseDefaultHomeStorageDirInTests(storageDir, homeDir) {
  if (process.env.VITEST === void 0 && process.env.VITEST_WORKER_ID === void 0) {
    return;
  }
  const resolved = (0, import_node_path94.resolve)(storageDir);
  for (const dev of [false, true]) {
    const agentsDir = (0, import_node_path94.resolve)(cursorAgentsDir({ homeDir, dev }));
    if (resolved === agentsDir || resolved.startsWith(agentsDir + import_node_path94.sep)) {
      throw new Error(
        `agent-host-daemon tests must inject storageDir; refusing ~/${dev ? CURSOR_AGENTS_DEV_DIR_NAME : CURSOR_AGENTS_DIR_NAME}`
      );
    }
  }
}
var import_node_crypto44, import_node_fs40, import_node_path94, AGENT_HOST_DAEMON_BLOBS_DIR_ENV, stderrHostStorageLogger, realClock, EXEC_CONFIG_KEY_PREFIX, SUBAGENT_CHILD_KEY_PREFIX, SESSION_DELETE_PENDING_KEY_PREFIX, SESSION_CREATE_OWNER_KEY_PREFIX, SUBAGENT_INVOCATION_KEY_PREFIX, DaemonSessionRecords;
var init_session_storage = __esm({
  "src/session-storage.ts"() {
    "use strict";
    import_node_crypto44 = require("node:crypto");
    import_node_fs40 = require("node:fs");
    import_node_path94 = require("node:path");
    init_runtime();
    init_storage();
    init_agent_host_surface_pb();
    init_listen();
    init_session_storage_reconciliation();
    AGENT_HOST_DAEMON_BLOBS_DIR_ENV = "AGENT_HOST_DAEMON_BLOBS_DIR";
    stderrHostStorageLogger = {
      info: (message) => {
        console.error(message);
      },
      warn: (message) => {
        console.error(message);
      },
      error: (message, error3) => {
        console.error(message, error3);
      }
    };
    realClock = {
      now: () => Date.now(),
      schedule: (delayMs, fn) => {
        const timer2 = setTimeout(fn, delayMs);
        return {
          dispose: () => {
            clearTimeout(timer2);
          }
        };
      }
    };
    EXEC_CONFIG_KEY_PREFIX = "agentHostDaemon:execConfig:";
    SUBAGENT_CHILD_KEY_PREFIX = "agentHostDaemon:subagentChild:";
    SESSION_DELETE_PENDING_KEY_PREFIX = "agentHostDaemon:sessionDeletePending:";
    SESSION_CREATE_OWNER_KEY_PREFIX = "agentHostDaemon:sessionCreateOwner:";
    SUBAGENT_INVOCATION_KEY_PREFIX = "agentHostDaemon:subagentInvocation:";
    DaemonSessionRecords = class {
      constructor(store, sessions, log5) {
        this.store = store;
        this.sessions = sessions;
        this.log = log5;
      }
      hasSession(sessionId) {
        return this.sessions.hasNativeSession(sessionId);
      }
      readSessionExecConfig(sessionId) {
        const raw = this.store.items.get(`${EXEC_CONFIG_KEY_PREFIX}${sessionId}`);
        return raw === void 0 ? void 0 : decodeSessionExecConfig(raw);
      }
      // An undecodable record reads as absent so the session still lists and
      // deletes; a hydrate reads it strictly and fails there.
      readSessionExecConfigLenient(sessionId) {
        try {
          return this.readSessionExecConfig(sessionId);
        } catch (error3) {
          this.log.warn(
            `[hostStorage] exec config for session ${sessionId} is unreadable (${error3 instanceof Error ? error3.name : typeof error3}); treating it as absent`
          );
          return void 0;
        }
      }
      writeSessionExecConfig(sessionId, config2) {
        this.store.items.set(`${EXEC_CONFIG_KEY_PREFIX}${sessionId}`, encodeSessionExecConfig(config2));
      }
      writeSessionExecConfigUnlessDeleting(sessionId, config2) {
        this.store.transaction(() => {
          if (this.sessionDeletePendingValue(sessionId) !== void 0) {
            throw new Error(
              `session ${sessionId} has a pending delete; retry after startup reconciliation`
            );
          }
          this.writeSessionExecConfig(sessionId, config2);
        });
      }
      restoreSessionExecConfigIfCurrent(args) {
        return this.store.transaction(() => {
          const current = this.readSessionExecConfig(args.sessionId);
          if (current === void 0 || !sessionExecConfigsEqual(current, args.expected)) {
            return false;
          }
          if (args.replacement === void 0) {
            this.deleteSessionExecConfig(args.sessionId);
          } else {
            this.writeSessionExecConfig(args.sessionId, args.replacement);
          }
          return true;
        });
      }
      deleteSessionExecConfig(sessionId) {
        this.store.items.delete(`${EXEC_CONFIG_KEY_PREFIX}${sessionId}`);
      }
      listSessionExecConfigSessionIds() {
        return this.store.items.keys(EXEC_CONFIG_KEY_PREFIX).map((key) => key.slice(EXEC_CONFIG_KEY_PREFIX.length));
      }
      tryAcquireSessionCreate(sessionId, pid) {
        return this.store.transaction(() => {
          if (this.sessionDeletePendingValue(sessionId) !== void 0) {
            return false;
          }
          this.store.items.set(sessionCreateOwnerKey(sessionId, pid), pid);
          return true;
        });
      }
      releaseSessionCreate(sessionId, pid) {
        this.store.items.delete(sessionCreateOwnerKey(sessionId, pid));
      }
      readSubagentChildSessionId(args) {
        const value = this.store.items.get(subagentChildKey(args));
        return typeof value === "string" && value.length > 0 ? value : void 0;
      }
      writeSubagentChildSessionId(args) {
        this.store.items.set(subagentChildKey(args), args.childSessionId);
      }
      deleteSubagentChildSessionId(args) {
        const key = subagentChildKey(args);
        this.store.transaction(() => {
          if (this.store.items.get(key) === args.childSessionId) {
            this.store.items.delete(key);
          }
        });
      }
      listSubagentChildSessionIds(parentSessionId) {
        return this.store.items.entries(`${SUBAGENT_CHILD_KEY_PREFIX}${parentSessionId}:`).flatMap(({ value }) => typeof value === "string" && value.length > 0 ? [value] : []);
      }
      deleteSubagentChildIndexForParent(parentSessionId) {
        for (const key of this.store.items.keys(`${SUBAGENT_CHILD_KEY_PREFIX}${parentSessionId}:`)) {
          this.store.items.delete(key);
        }
      }
      markSessionDeletePending(sessionId) {
        this.store.items.set(sessionDeletePendingKey(sessionId), true);
      }
      hasSessionDeletePending(sessionId) {
        return this.sessionDeletePendingValue(sessionId) !== void 0;
      }
      listSessionDeletePendingSessionIds() {
        return this.store.items.keys(SESSION_DELETE_PENDING_KEY_PREFIX).map((key) => key.slice(SESSION_DELETE_PENDING_KEY_PREFIX.length));
      }
      claimStartupReconciliation(sessionId, allowOrphanReclaim) {
        return this.store.transaction(() => {
          const owners = this.store.items.entries(sessionCreateOwnerKeyPrefix(sessionId));
          if (owners.some(({ value }) => sessionCreateOwnerBlocksReconciliation(value))) {
            return void 0;
          }
          for (const { key } of owners) {
            this.store.items.delete(key);
          }
          if (this.sessionDeletePendingValue(sessionId) !== void 0) {
            return { kind: "delete-pending" };
          }
          if (!allowOrphanReclaim || this.store.items.get(`${EXEC_CONFIG_KEY_PREFIX}${sessionId}`) !== void 0) {
            return void 0;
          }
          const marker17 = {
            kind: "orphan-reclaim",
            token: (0, import_node_crypto44.randomUUID)()
          };
          this.store.items.set(sessionDeletePendingKey(sessionId), marker17);
          return { kind: marker17.kind, token: marker17.token };
        });
      }
      cancelOrphanReclaim(sessionId, token) {
        this.store.transaction(() => {
          const marker17 = this.sessionDeletePendingValue(sessionId);
          if (isOrphanReclaimMarker(marker17) && marker17.token === token) {
            this.store.items.delete(sessionDeletePendingKey(sessionId));
          }
        });
      }
      deleteSessionDeletePending(sessionId) {
        this.store.items.delete(sessionDeletePendingKey(sessionId));
      }
      finishSessionDeleteRecords(sessionId) {
        this.store.transaction(() => {
          this.deleteDurableSubagentInvocationsForSession(sessionId);
          this.deleteSessionExecConfig(sessionId);
          this.deleteSubagentChildIndexForParent(sessionId);
          for (const key of this.store.items.keys(sessionCreateOwnerKeyPrefix(sessionId))) {
            this.store.items.delete(key);
          }
          this.deleteSessionDeletePending(sessionId);
        });
      }
      reportDeletePending(outcome) {
        let count2;
        try {
          count2 = this.store.items.keys(SESSION_DELETE_PENDING_KEY_PREFIX).length;
        } catch (error3) {
          void (error3 instanceof Error ? error3.name : typeof error3);
          return;
        }
        if (count2 === 0) {
          return;
        }
        this.warnSafely(`[hostStorage] daemon native delete pending outcome=${outcome} count=${count2}`);
      }
      reportPostKernelMetadataPersistenceFailure() {
        this.warnSafely("[hostStorage] daemon native post-kernel metadata persistence failed");
      }
      warnSafely(message) {
        try {
          this.log.warn(message);
        } catch (error3) {
          void (error3 instanceof Error ? error3.name : typeof error3);
        }
      }
      insertDurableSubagentInvocation(args) {
        const key = subagentInvocationKey(args);
        const existing = this.store.blobs.get(key);
        if (existing !== void 0) {
          return { inserted: false, record: existing };
        }
        this.store.blobs.set(key, args.record);
        return { inserted: true, record: args.record };
      }
      readDurableSubagentInvocation(args) {
        return this.store.blobs.get(subagentInvocationKey(args));
      }
      writeDurableSubagentInvocation(args) {
        this.store.blobs.set(subagentInvocationKey(args), args.record);
      }
      listDurableSubagentInvocationsByParentTool(args) {
        return this.listDurableSubagentInvocationsUnder(
          `${SUBAGENT_INVOCATION_KEY_PREFIX}${args.parentSessionId}:`
        ).filter((row) => row.parentToolCallId === args.parentToolCallId);
      }
      listDurableSubagentInvocations() {
        return this.listDurableSubagentInvocationsUnder(SUBAGENT_INVOCATION_KEY_PREFIX);
      }
      listDurableSubagentInvocationsUnder(keyPrefix) {
        return this.store.blobs.entries(keyPrefix).flatMap(({ key, value }) => {
          const parsed = parseSubagentInvocationKey(
            key,
            value
          );
          return parsed === void 0 ? [] : [parsed];
        });
      }
      deleteDurableSubagentInvocation(args) {
        this.store.blobs.delete(subagentInvocationKey(args));
      }
      deleteDurableSubagentInvocationsForSession(sessionId) {
        const covered = /* @__PURE__ */ new Set([sessionId]);
        let grew = true;
        while (grew) {
          grew = false;
          for (const row of this.listDurableSubagentInvocations()) {
            if (!covered.has(row.parentSessionId) && !covered.has(row.rootSessionId)) {
              continue;
            }
            const childSessionId = AgentHostDurableSubagentInvocationRecord.fromBinary(
              row.record
            ).childSessionId;
            if (childSessionId.length > 0 && !covered.has(childSessionId)) {
              covered.add(childSessionId);
              grew = true;
            }
          }
        }
        for (const row of this.listDurableSubagentInvocations()) {
          const childSessionId = AgentHostDurableSubagentInvocationRecord.fromBinary(
            row.record
          ).childSessionId;
          if (covered.has(row.parentSessionId) || covered.has(row.rootSessionId) || covered.has(childSessionId)) {
            this.deleteDurableSubagentInvocation(row);
          }
        }
      }
      withDurableSubagentInvocationTransaction(fn) {
        return this.store.transaction(fn);
      }
      sessionDeletePendingValue(sessionId) {
        return this.store.items.get(sessionDeletePendingKey(sessionId));
      }
    };
  }
});

Workspace state database (occurrence 1)

Source: out/vs/workbench/workbench.desktop.main.js (desktop) · bytes 30404928–30404939 · SHA-256 2fd673896676…

state.vscdb

Workspace state database (occurrence 2)

Source: out/vs/workbench/workbench.desktop.main.js (desktop) · bytes 37201170–37201181 · SHA-256 2fd673896676…

state.vscdb