[
  {
    "side": "before",
    "results": [
      {
        "side": "before",
        "run": 1,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-ff48b948-43d2-4950-8474-d7c3245da231",
              "requestId": "1d28f54b-a302-42e3-a367-84fe0b274249",
              "status": "finished",
              "result": "Primary change is moving Cursor Agent SDK work into a dedicated out-of-process worker.",
              "model": {
                "id": "default"
              },
              "durationMs": 8440,
              "usage": {
                "inputTokens": 21654,
                "outputTokens": 471,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22125,
                "reasoningTokens": 336
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe commit message must be a JSON object with keys \"subject\" and \"body\".\n\nThe primary change moves Cursor Agent SDK execution into a dedicated out-of-process worker. New files include CursorAgentSdkProcessRunner, CursorAgentSdkWorker, and CursorAgentSdkWorkerProtocol. The server now spawns this worker via ProviderOrchestrationAdapterInfrastructure. A shared SqliteLocalAgentStore per workspace was added with noop runEvents. The SDK version bumped from 1.4.1 to 1.4.2. Text generation updates were also included.\n\nDrafting the commit message now. The subject will be imperative and under 72 characters. The body will list key related changes as bullet points.",
                        "thinkingDurationMs": 4508
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "Primary change is moving Cursor Agent SDK work into a dedicated out-of-process worker."
                      }
                    },
                    {
                      "type": "toolCall",
                      "message": {
                        "type": "createPlan",
                        "args": {
                          "plan": "# Commit message\n\n```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, process runner, and protocol serialization\\n- Share one SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```\n"
                        },
                        "result": {
                          "status": "success",
                          "value": {}
                        }
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-34d597fe-10e3-4c12-bdb5-925b0ab7c671",
              "requestId": "69bbf595-9dd6-48f3-8dfe-0422a2720a22",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI and process runner for provider orchestration\\n- Ref-count shared SqliteLocalAgentStore per workspace; noop runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 10496,
              "usage": {
                "inputTokens": 43887,
                "outputTokens": 768,
                "cacheReadTokens": 43264,
                "cacheWriteTokens": 0,
                "totalTokens": 44655,
                "reasoningTokens": 555
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe commit message must be a JSON object with keys subject and body.\n\nThe primary change is isolating the Cursor Agent SDK into an out-of-process worker. This includes a new `CursorAgentSdkWorker`, a server CLI fast path, and switching provider orchestration to use `ProcessRunner`. It also includes a shared ref-counted `SqliteLocalAgentStore` per workspace and upgrading `@cursor/sdk` from 1.4.1 to 1.4.2.",
                        "thinkingDurationMs": 4455
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "Primary change is isolating the Cursor Agent SDK in an out-of-process worker; returning the commit message JSON."
                      }
                    },
                    {
                      "type": "toolCall",
                      "message": {
                        "type": "createPlan",
                        "args": {
                          "plan": ""
                        },
                        "result": {
                          "status": "error",
                          "error": {
                            "message": "Invalid arguments: [\n  {\n    \"expected\": \"string\",\n    \"code\": \"invalid_type\",\n    \"path\": [\n      \"plan\"\n    ],\n    \"message\": \"Invalid input: expected string, received object\"\n  }\n]"
                          }
                        }
                      }
                    },
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The CreatePlan tool expects plan as a string, not an object.\n\nThe user wants a JSON object with subject and body, not a plan.\n\nThis is a direct request for a JSON commit message, not a coding task requiring a plan. I will return the JSON object directly.",
                        "thinkingDurationMs": 2415
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI and process runner for provider orchestration\\n- Ref-count shared SqliteLocalAgentStore per workspace; noop runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add __cursor-sdk-worker CLI and process runner for provider orchestration\n- Ref-count shared SqliteLocalAgentStore per workspace; noop runEvents appends\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 24313
      },
      {
        "side": "before",
        "run": 2,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-7a6ebf17-2948-47b0-9249-ef73f104cc91",
              "requestId": "a328660c-ba8a-43f5-81b9-eecda8306c2d",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Isolate Cursor agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner; wire server orchestration to spawn it\\n- Ref-count one SqliteLocalAgentStore per workspace and no-op runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 8606,
              "usage": {
                "inputTokens": 21660,
                "outputTokens": 416,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22076,
                "reasoningTokens": 330
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe commit message must be a JSON object with `subject` and `body` keys.\n\nThe core change is isolating the Cursor agent SDK into an out-of-process worker. The commit will cover the new process runner, server CLI fast path, shared SqliteLocalAgentStore, and SDK version bump.\n\nSubject options include \"Isolate Cursor agent SDK in an out-of-process worker\" and \"Run Cursor agent SDK in a dedicated worker process\". The response will be a direct JSON object with subject and body, not a plan.",
                        "thinkingDurationMs": 4181
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Isolate Cursor agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner; wire server orchestration to spawn it\\n- Ref-count one SqliteLocalAgentStore per workspace and no-op runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.success",
            "result": {
              "subject": "Isolate Cursor agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker CLI, protocol, and process runner; wire server orchestration to spawn it\n- Ref-count one SqliteLocalAgentStore per workspace and no-op runEvents appends\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 13198
      },
      {
        "side": "before",
        "run": 3,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-5d0a0e92-3575-4c50-a74c-1dc0b300b684",
              "requestId": "0cad1361-d173-4280-b3f6-ea4f9039a546",
              "status": "finished",
              "result": "The primary change is isolating the Cursor Agent SDK in a dedicated out-of-process worker, with supporting store sharing and an SDK bump.",
              "model": {
                "id": "default"
              },
              "durationMs": 9157,
              "usage": {
                "inputTokens": 21657,
                "outputTokens": 543,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22200,
                "reasoningTokens": 343
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe changes isolate the Cursor Agent SDK in an out-of-process worker. The server CLI gains a fast path for this worker. Provider orchestration now uses a process runner instead of the in-process agent. A shared SqliteLocalAgentStore with ref-counting and noop runEvents was added per workspace. The @cursor/sdk dependency was upgraded from 1.4.1 to 1.4.2. Tests were updated accordingly.\n\nDrafting a subject line about isolating the Cursor Agent SDK in an out-of-process worker. The user explicitly wants a JSON object with subject and body, so I will return that directly rather than calling CreatePlan.",
                        "thinkingDurationMs": 4109
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "The primary change is isolating the Cursor Agent SDK in a dedicated out-of-process worker, with supporting store sharing and an SDK bump."
                      }
                    },
                    {
                      "type": "toolCall",
                      "message": {
                        "type": "createPlan",
                        "args": {
                          "plan": "# Commit message\n\nPrimary user/developer-visible change: Cursor Agent SDK runs out-of-process via a new `__cursor-sdk-worker` CLI path and process runner (not in-process in the server).\n\n```json\n{\n  \"subject\": \"Isolate Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker protocol, process runner, and __cursor-sdk-worker CLI\\n- Share ref-counted SqliteLocalAgentStore per workspace; noop runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```\n"
                        },
                        "result": {
                          "status": "success",
                          "value": {}
                        }
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-445a06ac-87d4-49e3-8b94-f1eb5f9a050c",
              "requestId": "5b2a812d-ae4a-452a-ae79-98301541d5d7",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI and NDJSON process runner\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 7615,
              "usage": {
                "inputTokens": 21657,
                "outputTokens": 456,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22113,
                "reasoningTokens": 379
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe commit message must be a JSON object with subject and body keys.\n\nThe staged changes cover an SDK upgrade, a new out-of-process Cursor SDK worker, and refactored provider orchestration. Shared SqliteLocalAgentStore now uses per-workspace ref-counting with noop runEvents. Text generation was updated and tests were added for the worker path.\n\nThe subject will be \"Run Cursor Agent SDK in an out-of-process worker\". I will return the JSON object directly without generating a plan.",
                        "thinkingDurationMs": 4819
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI and NDJSON process runner\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add __cursor-sdk-worker CLI and NDJSON process runner\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 19991
      },
      {
        "side": "before",
        "run": 4,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-62bb1c2b-7a02-42ca-9087-bde88ed474c2",
              "requestId": "02a8bedd-5b5a-49ba-9da6-d80723895baf",
              "status": "finished",
              "result": "Isolating the Cursor Agent SDK behind an out-of-process worker is the main change; the rest supports that.",
              "model": {
                "id": "default"
              },
              "durationMs": 9697,
              "usage": {
                "inputTokens": 21657,
                "outputTokens": 607,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22264,
                "reasoningTokens": 420
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes.\n\nThe commit message must be a JSON object with keys `subject` and `body`.\n\nThe staged changes isolate the Cursor Agent SDK into an out-of-process worker via a new ProcessRunner. The CLI now has a fast path for this worker. Provider orchestration switched to the process runner. A shared SqliteLocalAgentStore with ref-counting was added per workspace. The @cursor/sdk dependency was upgraded from 1.4.1 to 1.4.2. Tests were added.\n\nThe subject will be \"Run Cursor Agent SDK in an out-of-process worker\". I will return the JSON object directly without planning.",
                        "thinkingDurationMs": 5548
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "Isolating the Cursor Agent SDK behind an out-of-process worker is the main change; the rest supports that."
                      }
                    },
                    {
                      "type": "toolCall",
                      "message": {
                        "type": "createPlan",
                        "args": {
                          "plan": "# Commit message\n\nPrimary change: move Cursor Agent SDK into an out-of-process `__cursor-sdk-worker` with a process runner, plus shared workspace SQLite store leases and `@cursor/sdk` 1.4.2.\n\n```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```\n"
                        },
                        "result": {
                          "status": "success",
                          "value": {}
                        }
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-8b5f008d-e659-4ff5-a4c4-105d8d2ca072",
              "requestId": "af922ac0-a827-4ce1-826a-2e2f582c2552",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner wired into orchestration\\n- Share ref-counted workspace SQLite stores and skip run_events writes\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 5063,
              "usage": {
                "inputTokens": 21657,
                "outputTokens": 336,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 21993,
                "reasoningTokens": 258
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes.\n\nThe primary change is running the Cursor Agent SDK in an out-of-process worker. The subject line will be \"Run Cursor Agent SDK in an out-of-process worker\".",
                        "thinkingDurationMs": 944
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner wired into orchestration\\n- Share ref-counted workspace SQLite stores and skip run_events writes\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker CLI, protocol, and process runner wired into orchestration\n- Share ref-counted workspace SQLite stores and skip run_events writes\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 18030
      },
      {
        "side": "before",
        "run": 5,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-97162671-62de-4380-b1bb-2be897cc233c",
              "requestId": "c143eb62-56b0-4eb0-a3e3-cecc007eca6e",
              "status": "finished",
              "result": "The primary change is moving Cursor Agent SDK work into a dedicated out-of-process worker.\n\n```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner with session/text-generate RPCs\\n- Wire provider orchestration to spawn __cursor-sdk-worker instead of in-process SDK\\n- Ref-count shared SqliteLocalAgentStore per workspace and no-op runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 7214,
              "usage": {
                "inputTokens": 21657,
                "outputTokens": 451,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22108,
                "reasoningTokens": 325
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe primary change is isolating the Cursor Agent SDK into an out-of-process worker via a process runner. I am now drafting the commit message.\n\nThe subject is finalized as \"Run Cursor Agent SDK in an out-of-process worker\". The body will list the key changes. I will return the JSON object directly.",
                        "thinkingDurationMs": 2895
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "The primary change is moving Cursor Agent SDK work into a dedicated out-of-process worker.\n\n```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner with session/text-generate RPCs\\n- Wire provider orchestration to spawn __cursor-sdk-worker instead of in-process SDK\\n- Ref-count shared SqliteLocalAgentStore per workspace and no-op runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker CLI, protocol, and process runner with session/text-generate RPCs\n- Wire provider orchestration to spawn __cursor-sdk-worker instead of in-process SDK\n- Ref-count shared SqliteLocalAgentStore per workspace and no-op runEvents appends\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 8368
      },
      {
        "side": "before",
        "run": 6,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-9d532b59-6569-45f1-913a-04a6744b8d5c",
              "requestId": "78fb66a5-5224-48f8-b988-c168d9bc3279",
              "status": "finished",
              "result": "Primary change is moving the Cursor Agent SDK into an out-of-process worker; drafting the commit message JSON now.",
              "model": {
                "id": "default"
              },
              "durationMs": 10571,
              "usage": {
                "inputTokens": 21657,
                "outputTokens": 519,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22176,
                "reasoningTokens": 441
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes, and return a JSON object with keys `subject` and `body`.\n\nThe primary change is moving the Cursor Agent SDK out-of-process via a dedicated worker process. The diff also includes a server CLI fast path, provider orchestration switching to the process runner, a shared SqliteLocalAgentStore per workspace, and an SDK bump from 1.4.1 to 1.4.2.\n\nDrafting the commit message JSON now. The subject will be imperative and under 72 characters.\n\nThe subject is finalized as \"Isolate Cursor Agent SDK behind an out-of-process worker\". The body will list the NDJSON worker CLI, shared SQLite stores, and SDK bump. No plan is needed.",
                        "thinkingDurationMs": 7120
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "Primary change is moving the Cursor Agent SDK into an out-of-process worker; drafting the commit message JSON now."
                      }
                    },
                    {
                      "type": "toolCall",
                      "message": {
                        "type": "createPlan",
                        "args": {
                          "plan": "# Commit message for feature/cursor-sdk-worker"
                        },
                        "result": {
                          "status": "success",
                          "value": {}
                        }
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-7fc83e26-ac38-46c6-85de-34fc5dccdf45",
              "requestId": "ff39a1b9-d860-4971-bea6-b31f5cb31d9c",
              "status": "finished",
              "result": "The staged diff centers on isolating Cursor Agent SDK work in a subprocess worker, with shared workspace SQLite and the 1.4.2 bump as supporting pieces.",
              "model": {
                "id": "default"
              },
              "durationMs": 10329,
              "usage": {
                "inputTokens": 21657,
                "outputTokens": 508,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22165,
                "reasoningTokens": 354
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe commit message will cover the out-of-process Cursor SDK worker, new process runners and protocol, shared SqliteLocalAgentStore per workspace, and related test wiring.",
                        "thinkingDurationMs": 5662
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "The staged diff centers on isolating Cursor Agent SDK work in a subprocess worker, with shared workspace SQLite and the 1.4.2 bump as supporting pieces."
                      }
                    },
                    {
                      "type": "toolCall",
                      "message": {
                        "type": "createPlan",
                        "args": {
                          "plan": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI path and NDJSON process runner\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```\n"
                        },
                        "result": {
                          "status": "success",
                          "value": {}
                        }
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.error",
            "error": "TextGenerationError: Text generation failed in generateCommitMessage: Cursor SDK returned invalid structured output."
          }
        ],
        "success": false,
        "elapsedMs": 23241
      }
    ],
    "input": {
      "stagedPatch": "diff --git a/apps/server/package.json b/apps/server/package.json\nindex e9f211891a..8ece0aaa81 100644\n--- a/apps/server/package.json\n+++ b/apps/server/package.json\n@@ -37,7 +37,7 @@\n   },\n   \"dependencies\": {\n     \"@anthropic-ai/claude-agent-sdk\": \"^0.3.321\",\n-    \"@cursor/sdk\": \"1.4.1\",\n+    \"@cursor/sdk\": \"1.4.2\",\n     \"@effect/platform-node\": \"catalog:\",\n     \"@effect/platform-node-shared\": \"catalog:\",\n     \"@ff-labs/fff-node\": \"0.11.0\",\ndiff --git a/apps/server/src/binMain.ts b/apps/server/src/binMain.ts\nindex 0dabd73873..7d4c93fb04 100644\n--- a/apps/server/src/binMain.ts\n+++ b/apps/server/src/binMain.ts\n@@ -30,6 +30,12 @@ export async function runCliCommand() {\n     if (mode !== \"discover\" && mode !== \"model\") throw new Error(\"Unknown speech worker mode.\");\n     const { runNativeSpeechWorker } = await import(\"./speech/native.ts\");\n     await runNativeSpeechWorker(mode, process.argv[4]);\n+  } else if (command === \"__cursor-sdk-worker\") {\n+    const [NodeServices, { runCursorSdkWorker }] = await Promise.all([\n+      import(\"@effect/platform-node/NodeServices\"),\n+      import(\"@t3tools/provider-cursor/server/worker\"),\n+    ]);\n+    await runCursorSdkWorker(NodeServices.layer);\n   } else {\n     enableCliCompileCache();\n     // Windows desktop launches without stdin; attach before reading, except on fast paths using pipes.\ndiff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\nindex 8458b46b30..981f6847ef 100644\n--- a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\n+++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\n@@ -1,8 +1,14 @@\n+import * as NodeServices from \"@effect/platform-node/NodeServices\";\n import { assert, it } from \"@effect/vitest\";\n import { ProviderDriverKind } from \"@t3tools/contracts\";\n import * as IdAllocator from \"@t3tools/provider-core/server/IdAllocator\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n import * as Effect from \"effect/Effect\";\n import * as Layer from \"effect/Layer\";\n+import * as Path from \"effect/Path\";\n+import * as ChildProcess from \"effect/process/ChildProcess\";\n+import * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\n+import * as Stream from \"effect/Stream\";\n import * as SqlClient from \"effect/sql/SqlClient\";\n \n import * as SqlitePersistence from \"../persistence/Sqlite.ts\";\n@@ -40,3 +46,34 @@ it.effect(\"subagent threads stored under a legacy id keep it when re-derived\", (\n     );\n   }),\n );\n+\n+it.live(\"spawns the __cursor-sdk-worker CLI fast path and shuts down cleanly on close\", () =>\n+  Effect.scoped(\n+    Effect.gen(function* () {\n+      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n+      const path = yield* Path.Path;\n+      const executable = yield* HostProcess.ExecutablePath;\n+      const entry = yield* path.fromFileUrl(new URL(\"../bin.ts\", import.meta.url));\n+      const handle = yield* spawner.spawn(\n+        ChildProcess.make(executable, [entry, \"__cursor-sdk-worker\"], {\n+          stdin: { stream: \"pipe\", endOnDone: false },\n+          stdout: \"pipe\",\n+          stderr: \"pipe\",\n+        }),\n+      );\n+      yield* Stream.run(\n+        Stream.encodeText(Stream.make(`${JSON.stringify({ id: 1, type: \"close\" })}\\n`)),\n+        handle.stdin,\n+      );\n+      const stdout = yield* handle.stdout.pipe(Stream.decodeText(), Stream.mkString);\n+      const exitCode = Number(yield* handle.exitCode);\n+      assert.strictEqual(exitCode, 0);\n+      assert.deepStrictEqual(JSON.parse(stdout.trim()), {\n+        type: \"response\",\n+        id: 1,\n+        ok: true,\n+        result: null,\n+      });\n+    }),\n+  ).pipe(Effect.provide(NodeServices.layer)),\n+);\ndiff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\nindex b01735a7c2..ffb25e7daa 100644\n--- a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\n+++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\n@@ -1,13 +1,17 @@\n import * as Effect from \"effect/Effect\";\n import * as Layer from \"effect/Layer\";\n+import * as Path from \"effect/Path\";\n import * as SqlClient from \"effect/sql/SqlClient\";\n \n import * as ClaudeAdapterV2 from \"../orchestration-v2/Adapters/ClaudeAdapterV2.ts\";\n import * as CodexAdapterV2 from \"../orchestration-v2/Adapters/CodexAdapterV2.ts\";\n-import * as CursorAgentSdk from \"@t3tools/provider-cursor/server/CursorAgentSdk\";\n+import * as ProviderProcesses from \"../process/providerProcesses.ts\";\n+import type * as CursorAgentSdk from \"@t3tools/provider-cursor/server/CursorAgentSdk\";\n+import * as CursorAgentSdkProcessRunner from \"@t3tools/provider-cursor/server/CursorAgentSdkProcessRunner\";\n import * as CursorSdk from \"@t3tools/provider-cursor/server/CursorSdk\";\n import * as IdAllocator from \"@t3tools/provider-core/server/IdAllocator\";\n import * as ProviderContinuationRequests from \"@t3tools/provider-core/server/ProviderContinuationRequests\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n \n export type ProviderOrchestrationAdapterInfrastructure =\n   | ClaudeAdapterV2.ClaudeAgentSdkQueryRunner\n@@ -34,11 +38,39 @@ export const layerIdAllocator = Layer.unwrap(\n   }),\n );\n \n+const resolveCursorWorkerLaunch = Effect.gen(function* () {\n+  const path = yield* Path.Path;\n+  const command = yield* HostProcess.ExecutablePath;\n+  const isExecutable = yield* HostProcess.IsExecutable;\n+  const providerProcesses = yield* ProviderProcesses.ProviderProcesses;\n+  // In a bundle import.meta.url is bin.mjs; development and tests use this source module.\n+  const entry = yield* path\n+    .fromFileUrl(\n+      new URL(import.meta.url.endsWith(\".ts\") ? \"../bin.ts\" : \"./bin.mjs\", import.meta.url),\n+    )\n+    .pipe(Effect.orDie);\n+  return {\n+    command,\n+    args: [...(isExecutable ? [] : [entry]), \"__cursor-sdk-worker\"],\n+    ...(providerProcesses.register === undefined\n+      ? {}\n+      : { registerProcess: providerProcesses.register }),\n+  };\n+});\n+\n /** Reuse the continuation worker's exact layer reference so memoization shares one queue. */\n export const layer = Layer.mergeAll(\n   ClaudeAdapterV2.layerQueryRunner,\n   CodexAdapterV2.layerAppServerClientFactory,\n-  CursorAgentSdk.layer.pipe(Layer.provideMerge(CursorSdk.layer)),\n+  Layer.unwrap(\n+    Effect.gen(function* () {\n+      const path = yield* Path.Path;\n+      return CursorAgentSdkProcessRunner.layer(\n+        resolveCursorWorkerLaunch.pipe(Effect.provideService(Path.Path, path)),\n+      );\n+    }),\n+  ),\n+  CursorSdk.layer,\n   layerIdAllocator,\n   ProviderContinuationRequests.layer,\n );\ndiff --git a/packages/provider-cursor/package.json b/packages/provider-cursor/package.json\nindex e1d101a92f..dcd6bd0904 100644\n--- a/packages/provider-cursor/package.json\n+++ b/packages/provider-cursor/package.json\n@@ -23,6 +23,14 @@\n       \"types\": \"./src/server/CursorAgentSdk.ts\",\n       \"import\": \"./src/server/CursorAgentSdk.ts\"\n     },\n+    \"./server/CursorAgentSdkProcessRunner\": {\n+      \"types\": \"./src/server/CursorAgentSdkProcessRunner.ts\",\n+      \"import\": \"./src/server/CursorAgentSdkProcessRunner.ts\"\n+    },\n+    \"./server/worker\": {\n+      \"types\": \"./src/server/CursorAgentSdkWorker.ts\",\n+      \"import\": \"./src/server/CursorAgentSdkWorker.ts\"\n+    },\n     \"./server/accountUsage\": {\n       \"types\": \"./src/server/accountUsage.ts\",\n       \"import\": \"./src/server/accountUsage.ts\"\n@@ -45,7 +53,7 @@\n     \"test\": \"vp test run --config ../../vite.config.ts --dir .\"\n   },\n   \"dependencies\": {\n-    \"@cursor/sdk\": \"1.4.1\",\n+    \"@cursor/sdk\": \"1.4.2\",\n     \"@t3tools/contracts\": \"workspace:*\",\n     \"@t3tools/provider-core\": \"workspace:*\",\n     \"@t3tools/shared\": \"workspace:*\",\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\nindex 187ce35990..94ae520513 100644\n--- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\n+++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\n@@ -60,7 +60,7 @@ const cursorSdkMock = vi.hoisted(() => {\n       };\n     },\n   );\n-  const create = vi.fn(async () => ({\n+  const create = vi.fn(async (_options?: unknown) => ({\n     agentId: \"agent-cursor-agent-sdk-test\",\n     send,\n     close: agentClose,\n@@ -87,6 +87,8 @@ const cursorSdkMock = vi.hoisted(() => {\n     );\n   });\n \n+  const sqliteOpen = vi.fn<() => Promise<unknown>>(async () => undefined);\n+\n   return {\n     agentClose,\n     cancelRun,\n@@ -99,6 +101,7 @@ const cursorSdkMock = vi.hoisted(() => {\n     runSteer,\n     runWait,\n     send,\n+    sqliteOpen,\n     setAgentCloseFailure: (failure: unknown) => {\n       agentCloseFailure = failure;\n     },\n@@ -121,7 +124,7 @@ vi.mock(\"./sdk.ts\", () => ({\n     },\n     createAgentPlatform: vi.fn(),\n   }),\n-  loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: vi.fn() } }),\n+  loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: cursorSdkMock.sqliteOpen } }),\n }));\n \n const layerTest = CursorAgentSdk.layer.pipe(\n@@ -509,4 +512,101 @@ describe(\"CursorAgentSdkRunner\", () => {\n       assert.equal(yield* plain.steer!(\"later\"), \"revert_to_followup\");\n     }).pipe(Effect.provide(layerTest)),\n   );\n+\n+  it.effect(\n+    \"ref-counts one disposable SqliteLocalAgentStore with no-op runEvents per workspace\",\n+    () =>\n+      Effect.gen(function* () {\n+        const dispose = vi.fn(async () => {});\n+        const underlyingAppend = vi.fn(async () => {\n+          throw new Error(\"runEvents.append must not hit SQLite\");\n+        });\n+        const fakeStore = {\n+          agents: { get: vi.fn() },\n+          runs: { list: vi.fn() },\n+          checkpoints: { save: vi.fn() },\n+          runEvents: { append: underlyingAppend, list: vi.fn(), delete: vi.fn() },\n+          dispose,\n+        };\n+        cursorSdkMock.sqliteOpen.mockClear();\n+        cursorSdkMock.sqliteOpen.mockResolvedValueOnce(fakeStore);\n+        cursorSdkMock.create.mockClear();\n+\n+        const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;\n+        const session = yield* runner.open({\n+          operation: \"create\",\n+          options: { local: { cwd: \"/workspace/cursor-store-test\" } },\n+          threadId: ThreadId.make(\"thread-cursor-agent-sdk-store\"),\n+          providerSessionId: ProviderSessionId.make(\"provider-session-cursor-agent-sdk-store\"),\n+        });\n+        const peer = yield* runner.open({\n+          operation: \"create\",\n+          options: { local: { cwd: \"/workspace/cursor-store-test\" } },\n+          threadId: ThreadId.make(\"thread-cursor-agent-sdk-store-peer\"),\n+          providerSessionId: ProviderSessionId.make(\"provider-session-cursor-agent-sdk-store-peer\"),\n+        });\n+\n+        assert.deepStrictEqual(cursorSdkMock.sqliteOpen.mock.calls, [\n+          [{ workspaceRef: \"/workspace/cursor-store-test\" }],\n+        ]);\n+        const passedOptions = cursorSdkMock.create.mock.calls[0]?.[0] as\n+          | {\n+              readonly local?: {\n+                readonly store?: {\n+                  readonly agents: unknown;\n+                  readonly checkpoints: unknown;\n+                  readonly runEvents: {\n+                    readonly append: (event: {\n+                      readonly runId: string;\n+                      readonly eventType: string;\n+                      readonly payload?: unknown;\n+                    }) => Promise<{ readonly seq: number }>;\n+                  };\n+                };\n+              };\n+            }\n+          | undefined;\n+        const peerOptions = cursorSdkMock.create.mock.calls[1]?.[0] as typeof passedOptions;\n+        const passedStore = passedOptions?.local?.store;\n+        assert.isDefined(passedStore);\n+        assert.strictEqual(peerOptions?.local?.store, passedStore);\n+        assert.strictEqual(passedStore?.agents, fakeStore.agents);\n+        assert.strictEqual(passedStore?.checkpoints, fakeStore.checkpoints);\n+        const appended = yield* Effect.promise(() =>\n+          passedStore!.runEvents.append({\n+            runId: \"run-1\",\n+            eventType: \"text-delta\",\n+            payload: { text: \"hi\" },\n+          }),\n+        );\n+        assert.equal(appended.seq, 1);\n+        assert.equal(underlyingAppend.mock.calls.length, 0);\n+        assert.equal(dispose.mock.calls.length, 0);\n+\n+        // Closing one session keeps the shared workspace store alive; repeated close does not double-release.\n+        yield* session.close;\n+        yield* session.close;\n+        assert.equal(dispose.mock.calls.length, 0);\n+\n+        yield* peer.close;\n+        assert.equal(dispose.mock.calls.length, 1);\n+\n+        // Failed open disposes the newly opened store instead of leaking SQLite FDs.\n+        const failingDispose = vi.fn(async () => {});\n+        cursorSdkMock.sqliteOpen.mockResolvedValueOnce({ ...fakeStore, dispose: failingDispose });\n+        cursorSdkMock.create.mockRejectedValueOnce(new Error(\"boom\"));\n+        const failed = yield* runner\n+          .open({\n+            operation: \"create\",\n+            options: { local: { cwd: \"/workspace/cursor-store-fail\" } },\n+            threadId: ThreadId.make(\"thread-cursor-agent-sdk-store-fail\"),\n+            providerSessionId: ProviderSessionId.make(\n+              \"provider-session-cursor-agent-sdk-store-fail\",\n+            ),\n+          })\n+          .pipe(Effect.exit);\n+        assert(Exit.isFailure(failed));\n+        assert.equal(failingDispose.mock.calls.length, 1);\n+      }).pipe(Effect.provide(layerTest)),\n+  );\n });\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts\nindex 75b0232ebf..81b8208a5d 100644\n--- a/packages/provider-cursor/src/server/CursorAgentSdk.ts\n+++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts\n@@ -18,10 +18,12 @@ import {\n import * as Context from \"effect/Context\";\n import * as Deferred from \"effect/Deferred\";\n import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n import * as Layer from \"effect/Layer\";\n import * as Option from \"effect/Option\";\n import * as Ref from \"effect/Ref\";\n import * as Schema from \"effect/Schema\";\n+import * as Semaphore from \"effect/Semaphore\";\n \n import * as CursorSdk from \"./CursorSdk.ts\";\n import * as ProviderEventLoggers from \"@t3tools/provider-core/server/ProviderEventLoggers\";\n@@ -165,9 +167,19 @@ export interface CursorAgentSdkSession {\n    * The open agent keeps its old conversation in memory, so reopen it before the next send.\n    */\n   readonly rewindAfterRun?: (runId: string) => Effect.Effect<void, CursorAgentSdkRunnerError>;\n+  /** False once an out-of-process worker has terminated or started closing; absent on in-process sessions. */\n+  readonly isAlive?: () => boolean;\n   readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;\n }\n \n+export interface CursorAgentSdkTextGenerateInput {\n+  readonly prompt: string;\n+  readonly apiKey: string;\n+  readonly model: NonNullable<AgentOptions[\"model\"]>;\n+  readonly cwd: string;\n+  readonly stateRoot: string;\n+}\n+\n export class CursorAgentSdkRunner extends Context.Service<\n   CursorAgentSdkRunner,\n   {\n@@ -175,6 +187,10 @@ export class CursorAgentSdkRunner extends Context.Service<\n       input: CursorAgentSdkOpenInput,\n     ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;\n     readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;\n+    /** Absent on in-process test doubles; the out-of-process runner provides it. */\n+    readonly textGenerate?: (\n+      input: CursorAgentSdkTextGenerateInput,\n+    ) => Effect.Effect<RunResult, CursorAgentSdkRunnerError>;\n   }\n >()(\"@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner\") {}\n \n@@ -414,7 +430,7 @@ export function loggedCursorSendOptions(\n   };\n }\n \n-function makeCursorAgentSdkProtocolLogger(input: {\n+export function makeCursorAgentSdkProtocolLogger(input: {\n   readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;\n   readonly threadId: ThreadId;\n   readonly providerSessionId: OrchestrationV2ProviderSession[\"id\"];\n@@ -463,6 +479,60 @@ function subscribeShellStreamOutput(listener: (output: CursorShellStreamOutput)\n   };\n }\n \n+type CursorLocalStore = NonNullable<NonNullable<AgentOptions[\"local\"]>[\"store\"]>;\n+\n+interface DisposableCursorLocalStore extends CursorLocalStore {\n+  readonly dispose: () => Promise<void>;\n+}\n+\n+function isDisposableCursorLocalStore(value: unknown): value is DisposableCursorLocalStore {\n+  return (\n+    typeof value === \"object\" &&\n+    value !== null &&\n+    \"agents\" in value &&\n+    \"runs\" in value &&\n+    \"checkpoints\" in value &&\n+    \"runEvents\" in value &&\n+    \"dispose\" in value &&\n+    typeof value.dispose === \"function\"\n+  );\n+}\n+\n+// T3 persists its own event log and never tails SDK run_events; skipping per-delta SQLite\n+// run_events writes avoids synchronous BEGIN IMMEDIATE write locks and multi-GB index.db bloat.\n+export function withNoopCursorRunEvents(store: CursorLocalStore): CursorLocalStore {\n+  if (\n+    typeof store !== \"object\" ||\n+    store === null ||\n+    typeof store.runEvents?.append !== \"function\"\n+  ) {\n+    return store;\n+  }\n+  let seq = 0;\n+  return {\n+    agents: store.agents,\n+    runs: store.runs,\n+    checkpoints: store.checkpoints,\n+    runEvents: {\n+      append: async (event) => {\n+        seq += 1;\n+        return {\n+          runId: event.runId,\n+          seq,\n+          offset: String(seq),\n+          eventType: event.eventType,\n+          payload: event.payload ?? null,\n+          payloadRef: event.payloadRef ?? null,\n+          idempotencyKey: event.idempotencyKey ?? null,\n+          createdAt: 0,\n+        };\n+      },\n+      list: async () => ({ items: [] }),\n+      delete: async () => {},\n+    },\n+  };\n+}\n+\n interface CursorBackgroundShell {\n   readonly conversationId?: unknown;\n   readonly command?: unknown;\n@@ -548,6 +618,58 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n     },\n   );\n \n+  // Ref-count one SqliteLocalAgentStore per workspace so concurrent sessions share a single\n+  // index.db handle while still disposing handles, page caches, and FDs once the last one closes.\n+  interface WorkspaceStoreLease {\n+    readonly store: DisposableCursorLocalStore;\n+    readonly wrapped: CursorLocalStore;\n+    users: number;\n+  }\n+  const workspaceStores = new Map<string, WorkspaceStoreLease>();\n+  const workspaceStoreLock = yield* Semaphore.make(1);\n+  const acquireWorkspaceStore = (workspaceRef: string, method: string) =>\n+    workspaceStoreLock.withPermits(1)(\n+      Effect.suspend(() => {\n+        const existing = workspaceStores.get(workspaceRef);\n+        if (existing !== undefined) {\n+          existing.users += 1;\n+          return Effect.succeed(existing);\n+        }\n+        return Effect.tryPromise({\n+          try: async () => {\n+            const candidate = await sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef });\n+            return isDisposableCursorLocalStore(candidate) ? candidate : undefined;\n+          },\n+          catch: (cause) => runnerError(cause, method),\n+        }).pipe(\n+          Effect.map((opened) => {\n+            if (opened === undefined) return undefined;\n+            const lease: WorkspaceStoreLease = {\n+              store: opened,\n+              wrapped: withNoopCursorRunEvents(opened),\n+              users: 1,\n+            };\n+            workspaceStores.set(workspaceRef, lease);\n+            return lease;\n+          }),\n+        );\n+      }),\n+    );\n+  const releaseWorkspaceStore = (workspaceRef: string, lease: WorkspaceStoreLease) =>\n+    workspaceStoreLock.withPermits(1)(\n+      Effect.suspend(() => {\n+        lease.users -= 1;\n+        if (lease.users > 0) return Effect.void;\n+        if (workspaceStores.get(workspaceRef) === lease) {\n+          workspaceStores.delete(workspaceRef);\n+        }\n+        return Effect.tryPromise({\n+          try: () => lease.store.dispose(),\n+          catch: () => undefined,\n+        }).pipe(Effect.ignore);\n+      }),\n+    );\n+\n   return CursorAgentSdkRunner.of({\n     open: Effect.fn(\"CursorAgentSdkRunner.open\")(function* (input) {\n       const { Agent, createAgentPlatform } = yield* Effect.try({\n@@ -573,59 +695,85 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n       });\n \n       // Cursor uses cwd for both execution and store lookup; a moved thread keeps its original store.\n-      const storeCwd = input.storeCwd;\n-      const storePlatform =\n-        input.operation === \"resume\" &&\n-        storeCwd !== undefined &&\n-        storeCwd !== input.options.local?.cwd\n-          ? yield* Effect.tryPromise({\n-              try: () =>\n-                createAgentPlatform({\n-                  workspaceRef: storeCwd,\n-                  ...(input.options.local?.store === undefined\n-                    ? {}\n-                    : { localStore: input.options.local.store }),\n-                }),\n-              catch: (cause) => runnerError(cause, \"agent.resume\"),\n-            })\n-          : undefined;\n-      const agent = yield* Effect.tryPromise({\n-        try: () =>\n-          input.operation === \"create\"\n-            ? Agent.create(input.options)\n-            : storePlatform === undefined\n-              ? Agent.resume(input.agentId!, input.options)\n-              : storePlatform.resumeAgent(input.agentId!, input.options),\n-        catch: (cause) => runnerError(cause, `agent.${input.operation}`),\n-      });\n-      let shellListener: ((event: CursorBackgroundShellEvent) => void) | undefined;\n-\n-      yield* log({\n-        direction: \"incoming\",\n-        stage: \"decoded\",\n-        payload: {\n-          type: \"agent.opened\",\n-          agentId: agent.agentId,\n-        },\n-      });\n-\n       const cwd =\n         typeof input.options.local?.cwd === \"string\"\n           ? input.options.local.cwd\n           : input.options.local?.cwd?.[0];\n+      const storeCwd = input.storeCwd;\n+      const storeWorkspace =\n+        input.operation === \"resume\" && storeCwd !== undefined ? storeCwd : cwd;\n+      const ownedStoreLease =\n+        input.options.local?.store === undefined && storeWorkspace !== undefined\n+          ? yield* acquireWorkspaceStore(storeWorkspace, `agent.${input.operation}`)\n+          : undefined;\n+      let storeReleased = false;\n+      const disposeOwnedStore =\n+        ownedStoreLease === undefined || storeWorkspace === undefined\n+          ? Effect.void\n+          : Effect.suspend(() => {\n+              if (storeReleased) return Effect.void;\n+              storeReleased = true;\n+              return releaseWorkspaceStore(storeWorkspace, ownedStoreLease);\n+            });\n+      const effectiveStore =\n+        ownedStoreLease === undefined ? input.options.local?.store : ownedStoreLease.wrapped;\n+      const effectiveOptions: AgentOptions =\n+        effectiveStore === undefined || effectiveStore === input.options.local?.store\n+          ? input.options\n+          : {\n+              ...input.options,\n+              local: {\n+                ...input.options.local,\n+                store: effectiveStore,\n+              },\n+            };\n+\n+      const { storePlatform, agent } = yield* Effect.gen(function* () {\n+        const resolvedStorePlatform =\n+          input.operation === \"resume\" &&\n+          storeCwd !== undefined &&\n+          storeCwd !== input.options.local?.cwd\n+            ? yield* Effect.tryPromise({\n+                try: () =>\n+                  createAgentPlatform({\n+                    workspaceRef: storeCwd,\n+                    ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),\n+                  }),\n+                catch: (cause) => runnerError(cause, \"agent.resume\"),\n+              })\n+            : undefined;\n+        const openedAgent = yield* Effect.tryPromise({\n+          try: () =>\n+            input.operation === \"create\"\n+              ? Agent.create(effectiveOptions)\n+              : resolvedStorePlatform === undefined\n+                ? Agent.resume(input.agentId!, effectiveOptions)\n+                : resolvedStorePlatform.resumeAgent(input.agentId!, effectiveOptions),\n+          catch: (cause) => runnerError(cause, `agent.${input.operation}`),\n+        });\n+        yield* log({\n+          direction: \"incoming\",\n+          stage: \"decoded\",\n+          payload: {\n+            type: \"agent.opened\",\n+            agentId: openedAgent.agentId,\n+          },\n+        });\n+        return { storePlatform: resolvedStorePlatform, agent: openedAgent };\n+      }).pipe(Effect.onExit((exit) => (Exit.isFailure(exit) ? disposeOwnedStore : Effect.void)));\n+      let shellListener: ((event: CursorBackgroundShellEvent) => void) | undefined;\n+\n       const runOptions = {\n         runtime: \"local\" as const,\n         ...(cwd === undefined ? {} : { cwd }),\n-        ...(input.options.local?.store === undefined ? {} : { store: input.options.local.store }),\n+        ...(effectiveStore === undefined ? {} : { store: effectiveStore }),\n       };\n       let abandonedRunRecoveryAvailable = input.operation === \"resume\";\n       const storeView = async () =>\n         storePlatform ??\n         (await createAgentPlatform({\n           ...(cwd === undefined ? {} : { workspaceRef: cwd }),\n-          ...(input.options.local?.store === undefined\n-            ? {}\n-            : { localStore: input.options.local.store }),\n+          ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),\n         }));\n \n       return {\n@@ -879,9 +1027,7 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n                   ? Agent.messages.list(agent.agentId, {\n                       runtime: \"local\",\n                       ...(cwd === undefined ? {} : { cwd }),\n-                      ...(input.options.local?.store === undefined\n-                        ? {}\n-                        : { store: input.options.local.store }),\n+                      ...(effectiveStore === undefined ? {} : { store: effectiveStore }),\n                     })\n                   : storePlatform.getAgentMessages(agent.agentId),\n               catch: (cause) => runnerError(cause, \"agent.messages.list\"),\n@@ -1010,6 +1156,7 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n               catch: (cause) => runnerError(cause, \"agent.close\"),\n             }),\n           ),\n+          Effect.ensuring(disposeOwnedStore),\n         ),\n       } satisfies CursorAgentSdkSession;\n     }),\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts\nnew file mode 100644\nindex 0000000000..430907b101\n--- /dev/null\n+++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts\n@@ -0,0 +1,742 @@\n+import * as NodeServices from \"@effect/platform-node/NodeServices\";\n+import { assert, describe, it } from \"@effect/vitest\";\n+import { ProviderSessionId, ThreadId } from \"@t3tools/contracts\";\n+import { AgentScope } from \"@t3tools/shared/AgentScope\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n+import * as Deferred from \"effect/Deferred\";\n+import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n+import * as Fiber from \"effect/Fiber\";\n+import * as FileSystem from \"effect/FileSystem\";\n+import * as Path from \"effect/Path\";\n+\n+import * as CursorAgentSdk from \"./CursorAgentSdk.ts\";\n+import * as CursorAgentSdkProcessRunner from \"./CursorAgentSdkProcessRunner.ts\";\n+import {\n+  deserializeRunResult,\n+  deserializeWorkerError,\n+  serializeRunResult,\n+  serializeWorkerError,\n+} from \"./CursorAgentSdkWorkerProtocol.ts\";\n+import { isCursorSdkError, tagCursorSdkError } from \"./sdk.ts\";\n+\n+// Minimal fake worker script implementing the NDJSON worker protocol in a real child Node process.\n+const FAKE_WORKER_SCRIPT = `\n+const readline = require(\"node:readline\");\n+const rawWrite = process.stdout.write.bind(process.stdout);\n+const send = (msg) => rawWrite(JSON.stringify(msg) + \"\\\\n\");\n+const mode = process.env.FAKE_WORKER_MODE || \"ok\";\n+\n+const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });\n+rl.on(\"line\", (line) => {\n+  if (!line.trim()) return;\n+  const req = JSON.parse(line);\n+  if (req.type === \"open\") {\n+    if (mode === \"config-error\") {\n+      send({\n+        type: \"response\",\n+        id: req.id,\n+        ok: false,\n+        error: {\n+          method: \"agent.create\",\n+          cause: {\n+            name: \"ConfigurationError\",\n+            message: \"Cannot use this model: bad-model\",\n+            sdkErrorKind: \"ConfigurationError\",\n+          },\n+        },\n+      });\n+      return;\n+    }\n+    rawWrite(\"non-json noise that must be ignored\\\\n\");\n+    send({ type: \"response\", id: req.id, ok: true, result: { agentId: \"agent-worker-1\" } });\n+    return;\n+  }\n+  if (req.type === \"send\") {\n+    if (mode === \"hang-send\") {\n+      send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.started\", runId: \"pending\", agentId: \"agent-worker-1\" } } });\n+      return;\n+    }\n+    if (mode === \"crash-mid-run\") {\n+      send({ type: \"response\", id: req.id, ok: true, result: { runId: \"run-crash\", agentId: \"agent-worker-1\" } });\n+      process.stderr.write(\"fatal worker boom\\\\n\");\n+      process.exit(17);\n+      return;\n+    }\n+    // Emit an early delta before the send response to verify parent buffering/ordering.\n+    send({ type: \"delta\", sendId: req.id, update: { type: \"text-delta\", text: \"early-\" } });\n+    send({ type: \"response\", id: req.id, ok: true, result: { runId: \"run-worker-1\", agentId: \"agent-worker-1\" } });\n+    if (mode === \"cancel\") {\n+      return;\n+    }\n+    send({ type: \"delta\", sendId: req.id, update: { type: \"text-delta\", text: \"late\" } });\n+    send({\n+      type: \"runDone\",\n+      sendId: req.id,\n+      ok: true,\n+      result: {\n+        id: \"run-worker-1\",\n+        requestId: \"req-1\",\n+        status: \"finished\",\n+        result: \"early-late\",\n+        model: { id: \"default\" },\n+        durationMs: 5,\n+      },\n+    });\n+    if (mode === \"exit-after-done\") {\n+      rawWrite(\"\", () => process.exit(0));\n+    }\n+    if (mode === \"background-shell\" && req.listenBackgroundShells) {\n+      send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"started\", id: \"sh-1\", pid: 4101, command: \"sleep 60\" } });\n+      send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"started\", id: \"sh-2\", pid: 4102, command: \"tail -f\" } });\n+    }\n+    return;\n+  }\n+  if (req.type === \"stopBackgroundShell\") {\n+    send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"ended\", id: req.shellId, pid: 4101, command: \"sleep 60\", stopped: true, exitCode: undefined, outputPath: undefined } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    if (mode === \"background-shell\") {\n+      rawWrite(\"\", () => process.exit(19));\n+    }\n+    return;\n+  }\n+  if (req.type === \"steer\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: \"complete_delivered\" });\n+    return;\n+  }\n+  if (req.type === \"cancel\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.cancel\", runId: \"run-worker-1\" } } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    send({\n+      type: \"runDone\",\n+      sendId: req.sendId,\n+      ok: true,\n+      result: {\n+        id: \"run-worker-1\",\n+        requestId: \"req-1\",\n+        status: \"cancelled\",\n+        model: { id: \"default\" },\n+        durationMs: 2,\n+      },\n+    });\n+    return;\n+  }\n+  if (req.type === \"listMessages\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: [{ id: \"m1\", role: \"assistant\", text: \"early-late\" }] });\n+    return;\n+  }\n+  if (req.type === \"readContextUsage\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: { usedTokens: 120, maxTokens: 1000 } });\n+    return;\n+  }\n+  if (req.type === \"runCheckpointed\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: req.runId === \"run-worker-1\" });\n+    return;\n+  }\n+  if (req.type === \"rewindAfterRun\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"textGenerate\" && mode === \"hang-text\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.started\", runId: \"text\", agentId: \"text\" } } });\n+    return;\n+  }\n+  if (req.type === \"cancelTextGenerate\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.cancel\", runId: \"text\" } } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"textGenerate\") {\n+    if (mode === \"rate-limit-text\") {\n+      send({\n+        type: \"response\",\n+        id: req.id,\n+        ok: true,\n+        result: {\n+          id: \"run-tg-1\",\n+          requestId: \"req-tg-1\",\n+          status: \"error\",\n+          model: { id: \"default\" },\n+          durationMs: 3,\n+          error: {\n+            name: \"RateLimitError\",\n+            message: \"Too many requests\",\n+            code: \"PRO_USER_USAGE_LIMIT\",\n+            status: 429,\n+            sdkErrorKind: \"CursorSdkError\",\n+          },\n+        },\n+      });\n+      return;\n+    }\n+    send({\n+      type: \"response\",\n+      id: req.id,\n+      ok: true,\n+      result: {\n+        id: \"run-tg-1\",\n+        requestId: \"req-tg-1\",\n+        status: \"finished\",\n+        result: JSON.stringify({ title: \"Out of process\" }),\n+        model: { id: \"default\" },\n+        durationMs: 3,\n+      },\n+    });\n+    return;\n+  }\n+  if (req.type === \"closeSession\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"close\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    rawWrite(\"\", () => process.exit(0));\n+  }\n+});\n+rl.on(\"close\", () => process.exit(0));\n+`;\n+\n+const openInput = {\n+  operation: \"create\" as const,\n+  options: { model: { id: \"default\" } },\n+  threadId: ThreadId.make(\"thread-worker-test\"),\n+  providerSessionId: ProviderSessionId.make(\"provider-session-worker-test\"),\n+};\n+\n+describe(\"CursorAgentSdkWorkerProtocol\", () => {\n+  it(\"preserves SDK error classification, rate limits, and abort causes without loading @cursor/sdk\", () => {\n+    const configErr = tagCursorSdkError(\n+      new Error(\"Cannot use this model: mystery\"),\n+      \"ConfigurationError\",\n+    );\n+    const restoredConfig = deserializeWorkerError(serializeWorkerError(configErr));\n+    assert.isTrue(isCursorSdkError(restoredConfig, \"ConfigurationError\"));\n+    assert.isTrue(isCursorSdkError(restoredConfig, \"CursorSdkError\"));\n+    assert.isFalse(isCursorSdkError(restoredConfig, \"AuthenticationError\"));\n+\n+    const rateErr = Object.assign(new Error(\"Quota exceeded\"), {\n+      name: \"RateLimitError\",\n+      code: \"PRO_USER_USAGE_LIMIT\",\n+      status: 429,\n+    });\n+    const restoredResult = deserializeRunResult(\n+      serializeRunResult({\n+        id: \"r1\",\n+        requestId: \"req1\",\n+        status: \"error\",\n+        model: { id: \"default\" },\n+        durationMs: 1,\n+        error: rateErr,\n+      } as never),\n+    );\n+    assert.isTrue(CursorAgentSdk.isCursorUsageLimitError(restoredResult.error));\n+    assert.equal(restoredResult.error?.message, \"Quota exceeded\");\n+\n+    const abortInner = Object.assign(new Error(\"aborted\"), { name: \"AbortError\" });\n+    const wrappedAbort = new Error(\"outer\", { cause: abortInner });\n+    const restoredAbort = deserializeWorkerError(serializeWorkerError(wrappedAbort));\n+    assert.isTrue(CursorAgentSdk.isCursorCancellationError(restoredAbort));\n+\n+    const nullProto = Object.create(null) as Record<string, unknown>;\n+    const restoredNullProto = deserializeWorkerError(serializeWorkerError(nullProto));\n+    assert.equal(restoredNullProto.message, \"[Unserializable error]\");\n+  });\n+});\n+\n+describe(\"CursorAgentSdkProcessRunner\", () => {\n+  const writeFakeWorker = Effect.gen(function* () {\n+    const fs = yield* FileSystem.FileSystem;\n+    const path = yield* Path.Path;\n+    const dir = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-cursor-worker-test-\" });\n+    const scriptPath = path.join(dir, \"fake-worker.cjs\");\n+    yield* fs.writeFileString(scriptPath, FAKE_WORKER_SCRIPT);\n+    return scriptPath;\n+  });\n+\n+  it.live(\n+    \"runs a full session out of process with ordered deltas, scope hooks, and clean shutdown\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const registeredPids: Array<number> = [];\n+          const unregisteredPids: Array<number> = [];\n+          const stoppedUnits: Array<string> = [];\n+          const protocolEvents: Array<string> = [];\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              registerProcess: (pid) => {\n+                registeredPids.push(pid);\n+                return () => unregisteredPids.push(pid);\n+              },\n+            }),\n+            protocolLoggerFor: () => (event) =>\n+              Effect.sync(() => {\n+                protocolEvents.push(event.payload.type);\n+              }),\n+          }).pipe(\n+            Effect.provideService(AgentScope, {\n+              wrap: ({ command, args, name }) =>\n+                Effect.succeed({ command, args, unit: `unit-${name}` }),\n+              oomKilled: () => Effect.succeed(false),\n+              stop: (unit) =>\n+                Effect.sync(() => {\n+                  stoppedUnits.push(unit);\n+                }),\n+              kill: () => Effect.succeed(false),\n+              clear: () => Effect.void,\n+            }),\n+          );\n+\n+          const session = yield* runner.open(openInput);\n+          assert.equal(session.agentId, \"agent-worker-1\");\n+          assert.isTrue(session.isAlive?.());\n+          const otherSession = yield* runner.open({\n+            ...openInput,\n+            threadId: ThreadId.make(\"thread-worker-test-2\"),\n+            providerSessionId: ProviderSessionId.make(\"provider-session-worker-test-2\"),\n+          });\n+          yield* otherSession.close;\n+          assert.isFalse(otherSession.isAlive?.());\n+          assert.isTrue(session.isAlive?.());\n+          assert.lengthOf(registeredPids, 1);\n+          assert.deepEqual(unregisteredPids, []);\n+\n+          const receivedDeltas: Array<string> = [];\n+          const firstDeltaGate = yield* Deferred.make<void>();\n+          const run = yield* session.send({\n+            message: \"hi\",\n+            onDelta: (update) =>\n+              Effect.gen(function* () {\n+                const text = (update as { readonly text?: string }).text ?? \"\";\n+                if (text === \"early-\") {\n+                  yield* Deferred.succeed(firstDeltaGate, undefined);\n+                }\n+                receivedDeltas.push(text);\n+              }),\n+          });\n+          assert.equal(run.runId, \"run-worker-1\");\n+          yield* Deferred.await(firstDeltaGate);\n+\n+          const steerOutcome = yield* run.steer!(\"change course\");\n+          assert.equal(steerOutcome, \"complete_delivered\");\n+\n+          const result = yield* run.wait;\n+          assert.equal(result.status, \"finished\");\n+          assert.equal(result.result, \"early-late\");\n+          assert.deepEqual(receivedDeltas, [\"early-\", \"late\"]);\n+\n+          const [messagesA, messagesB] = yield* Effect.all(\n+            [session.listMessages, session.listMessages],\n+            { concurrency: \"unbounded\" },\n+          );\n+          assert.lengthOf(messagesA, 1);\n+          assert.lengthOf(messagesB, 1);\n+          const usage = yield* session.readContextUsage!;\n+          assert.deepEqual(usage, { usedTokens: 120, maxTokens: 1000 });\n+          assert.isTrue(yield* session.runCheckpointed!(\"run-worker-1\"));\n+          assert.isFalse(yield* session.runCheckpointed!(\"other\"));\n+          yield* session.rewindAfterRun!(\"run-worker-1\");\n+          yield* session.close;\n+          assert.isFalse(session.isAlive?.());\n+\n+          assert.deepEqual(unregisteredPids, registeredPids);\n+          assert.deepEqual(stoppedUnits, [\"unit-cursor-sdk\"]);\n+          assert.include(protocolEvents, \"agent.open\");\n+          assert.include(protocolEvents, \"agent.opened\");\n+          assert.include(protocolEvents, \"run.started\");\n+          assert.include(protocolEvents, \"interaction.update\");\n+          assert.include(protocolEvents, \"run.completed\");\n+          assert.include(protocolEvents, \"agent.close\");\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"preserves ConfigurationError classification across IPC and cleans up on open failure\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          let unregistered = false;\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"config-error\" },\n+              registerProcess: () => () => {\n+                unregistered = true;\n+              },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const error = yield* Effect.flip(runner.open(openInput));\n+          assert.isTrue(isCursorSdkError(error.cause, \"ConfigurationError\"));\n+          assert.isTrue(\n+            error.cause instanceof Error &&\n+              error.cause.message.startsWith(\"Cannot use this model:\"),\n+          );\n+          assert.isTrue(unregistered);\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"fails run.wait with exit code and stderr when the worker crashes mid-run\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const unregistered = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"crash-mid-run\" },\n+            registerProcess: () => () => {\n+              Deferred.doneUnsafe(unregistered, Exit.void);\n+            },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+\n+        const session = yield* runner.open(openInput);\n+        const run = yield* session.send({ message: \"hi\" });\n+        const error = yield* Effect.flip(run.wait);\n+        const msg = CursorAgentSdk.cursorSdkFailureMessage(error);\n+        assert.include(msg, \"code 17\");\n+        assert.notInclude(msg, \"fatal worker boom\");\n+        const diagnostic = error.cause instanceof Error ? error.cause.cause : undefined;\n+        assert.isTrue(\n+          diagnostic instanceof Error && diagnostic.message.includes(\"fatal worker boom\"),\n+        );\n+        // Dead worker scope tears down immediately instead of waiting for sessions to close.\n+        yield* Deferred.await(unregistered);\n+        assert.isFalse(session.isAlive?.());\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"preserves an already-received runDone when the worker exits while onDelta is running\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const workerTerminated = yield* Deferred.make<void>();\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"exit-after-done\" },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+            onWorkerTerminated: () => {\n+              Deferred.doneUnsafe(workerTerminated, Exit.void);\n+            },\n+          });\n+\n+          const session = yield* runner.open(openInput);\n+          const deltaStarted = yield* Deferred.make<void>();\n+          const releaseDelta = yield* Deferred.make<void>();\n+          const run = yield* session.send({\n+            message: \"hi\",\n+            onDelta: (update) =>\n+              Effect.gen(function* () {\n+                if ((update as { readonly text?: string }).text === \"early-\") {\n+                  yield* Deferred.succeed(deltaStarted, undefined);\n+                  yield* Deferred.await(releaseDelta);\n+                }\n+              }),\n+          });\n+          yield* Deferred.await(deltaStarted);\n+          yield* Deferred.await(workerTerminated);\n+          yield* Deferred.succeed(releaseDelta, undefined);\n+          const result = yield* run.wait;\n+          assert.equal(result.status, \"finished\");\n+          assert.equal(result.result, \"early-late\");\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"cancels a started run when send is interrupted before handing it off\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const startedLogged = yield* Deferred.make<void>();\n+        const cancelled = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"cancel\" },\n+          }),\n+          protocolLoggerFor: () => (event) => {\n+            if (event.payload.type === \"run.started\") {\n+              return Deferred.succeed(startedLogged, undefined).pipe(Effect.andThen(Effect.never));\n+            }\n+            if (event.payload.type === \"run.cancel\" && event.direction === \"incoming\") {\n+              return Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid);\n+            }\n+            return Effect.void;\n+          },\n+        });\n+        const session = yield* runner.open(openInput);\n+        const sending = yield* Effect.forkChild(session.send({ message: \"hi\" }));\n+        yield* Deferred.await(startedLogged);\n+        yield* Fiber.interrupt(sending);\n+        yield* Deferred.await(cancelled);\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"closes the session when send is interrupted after transmission before acknowledgment\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const receivedByWorker = yield* Deferred.make<void>();\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"hang-send\" },\n+            }),\n+            protocolLoggerFor: () => (event) =>\n+              event.payload.type === \"run.started\"\n+                ? Deferred.succeed(receivedByWorker, undefined).pipe(Effect.asVoid)\n+                : Effect.void,\n+          });\n+\n+          const session = yield* runner.open(openInput);\n+          assert.isTrue(session.isAlive?.());\n+          const sending = yield* Effect.forkChild(session.send({ message: \"hi\" }));\n+          yield* Deferred.await(receivedByWorker);\n+          yield* Fiber.interrupt(sending);\n+          assert.isFalse(session.isAlive?.());\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"cancels an interrupted text generation in a worker that other sessions keep alive\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const received = yield* Deferred.make<void>();\n+        const cancelled = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"hang-text\" },\n+          }),\n+          protocolLoggerFor: () => (event) =>\n+            event.payload.type === \"run.started\"\n+              ? Deferred.succeed(received, undefined).pipe(Effect.asVoid)\n+              : event.payload.type === \"run.cancel\"\n+                ? Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid)\n+                : Effect.void,\n+        });\n+        const session = yield* runner.open(openInput);\n+        const generating = yield* Effect.forkChild(\n+          runner.textGenerate!({\n+            prompt: \"title\",\n+            apiKey: \"key\",\n+            model: { id: \"default\" },\n+            cwd: \"/tmp\",\n+            stateRoot: \"/tmp\",\n+          }),\n+        );\n+        yield* Deferred.await(received);\n+        yield* Fiber.interrupt(generating);\n+        yield* Deferred.await(cancelled);\n+        assert.isTrue(session.isAlive?.());\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"forwards cancel and runs textGenerate in a disposable child process\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+\n+        const cancelRunner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"cancel\" },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+        const session = yield* cancelRunner.open(openInput);\n+        const run = yield* session.send({ message: \"hi\" });\n+        yield* run.cancel;\n+        const cancelled = yield* run.wait;\n+        assert.equal(cancelled.status, \"cancelled\");\n+        yield* session.close;\n+\n+        let textGenUnregistered = false;\n+        const textGenRunner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"rate-limit-text\" },\n+            registerProcess: () => () => {\n+              textGenUnregistered = true;\n+            },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+        const textResult = yield* textGenRunner.textGenerate!({\n+          prompt: \"title\",\n+          apiKey: \"key\",\n+          model: { id: \"default\" },\n+          cwd: \"/tmp\",\n+          stateRoot: \"/tmp\",\n+        });\n+        assert.equal(textResult.status, \"error\");\n+        assert.isTrue(CursorAgentSdk.isCursorUsageLimitError(textResult.error));\n+        assert.isTrue(textGenUnregistered);\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"settles active runs on a closed session without disrupting peer sessions on the shared worker\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const registeredPids: Array<number> = [];\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"cancel\" },\n+              registerProcess: (pid) => {\n+                registeredPids.push(pid);\n+                return () => {};\n+              },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const sessionA = yield* runner.open(openInput);\n+          const sessionB = yield* runner.open({\n+            ...openInput,\n+            threadId: ThreadId.make(\"thread-worker-test-peer\"),\n+            providerSessionId: ProviderSessionId.make(\"provider-session-worker-test-peer\"),\n+          });\n+          assert.lengthOf(registeredPids, 1);\n+\n+          // Start a run on sessionA that stays pending, then close sessionA while sessionB keeps the worker alive.\n+          const runA = yield* sessionA.send({ message: \"hi\" });\n+          const waitA = yield* Effect.forkChild(Effect.flip(runA.wait));\n+          yield* sessionA.close;\n+          const errorA = yield* Fiber.join(waitA);\n+          assert.include(CursorAgentSdk.cursorSdkFailureMessage(errorA), \"closed\");\n+          assert.isFalse(sessionA.isAlive?.());\n+          assert.isTrue(sessionB.isAlive?.());\n+          assert.lengthOf(yield* sessionB.listMessages, 1);\n+          yield* sessionB.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"forwards background shell events across IPC, routes stop(), and ends orphans on worker crash\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"background-shell\" },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const events: Array<object> = [];\n+          const startedFirst = yield* Deferred.make<() => void>();\n+          const bothEnded = yield* Deferred.make<void>();\n+          let endedCount = 0;\n+\n+          const session = yield* runner.open(openInput);\n+          const run = yield* session.send({\n+            message: \"watch it\",\n+            onBackgroundShell: (event) =>\n+              Effect.gen(function* () {\n+                if (event.type === \"started\") {\n+                  const { stop, ...started } = event;\n+                  events.push(started);\n+                  if (event.id === \"sh-1\") yield* Deferred.succeed(startedFirst, stop);\n+                  return;\n+                }\n+                events.push(event);\n+                endedCount += 1;\n+                if (endedCount === 2) yield* Deferred.succeed(bothEnded, undefined);\n+              }),\n+          });\n+          yield* run.wait;\n+\n+          // Stopping sh-1 triggers a worker-side ended event, then the fake worker crashes to\n+          // verify sh-2 gets a synthesized ended(stopped: true) event.\n+          const stopFirst = yield* Deferred.await(startedFirst);\n+          stopFirst();\n+          yield* Deferred.await(bothEnded);\n+\n+          assert.deepEqual(events, [\n+            { type: \"started\", id: \"sh-1\", pid: 4101, command: \"sleep 60\" },\n+            { type: \"started\", id: \"sh-2\", pid: 4102, command: \"tail -f\" },\n+            {\n+              type: \"ended\",\n+              id: \"sh-1\",\n+              pid: 4101,\n+              command: \"sleep 60\",\n+              stopped: true,\n+              exitCode: undefined,\n+              outputPath: undefined,\n+            },\n+            {\n+              type: \"ended\",\n+              id: \"sh-2\",\n+              pid: 4102,\n+              command: \"tail -f\",\n+              stopped: true,\n+              exitCode: undefined,\n+              outputPath: undefined,\n+            },\n+          ]);\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+});\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts\nnew file mode 100644\nindex 0000000000..ed97c62288\n--- /dev/null\n+++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts\n@@ -0,0 +1,1167 @@\n+import type { AgentMessage, InteractionUpdate, RunResult, SteerAckOutcome } from \"@cursor/sdk\";\n+import * as ProviderEventLoggers from \"@t3tools/provider-core/server/ProviderEventLoggers\";\n+import { AgentScope } from \"@t3tools/shared/AgentScope\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n+import * as Cause from \"effect/Cause\";\n+import * as Deferred from \"effect/Deferred\";\n+import * as Duration from \"effect/Duration\";\n+import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n+import * as Fiber from \"effect/Fiber\";\n+import * as Layer from \"effect/Layer\";\n+import * as Option from \"effect/Option\";\n+import * as ChildProcess from \"effect/process/ChildProcess\";\n+import * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\n+import * as Queue from \"effect/Queue\";\n+import * as Ref from \"effect/Ref\";\n+import * as Scope from \"effect/Scope\";\n+import * as Semaphore from \"effect/Semaphore\";\n+import * as Stream from \"effect/Stream\";\n+\n+import * as CursorAgentSdk from \"./CursorAgentSdk.ts\";\n+import {\n+  type CursorWorkerMessage,\n+  type CursorWorkerRequest,\n+  type CursorWorkerResponsePayload,\n+  type SerializedRunResult,\n+  type SerializedRunnerFailure,\n+  decodeWorkerFrame,\n+  deserializeRunResult,\n+  deserializeWorkerError,\n+  encodeWorkerFrame,\n+} from \"./CursorAgentSdkWorkerProtocol.ts\";\n+\n+const WORKER_CLOSE_TIMEOUT = Duration.seconds(3);\n+const WORKER_EXIT_TIMEOUT = Duration.seconds(2);\n+const MAX_STDERR_CHARS = 8_192;\n+\n+export interface CursorSdkWorkerLaunch {\n+  readonly command: string;\n+  readonly args: ReadonlyArray<string>;\n+  readonly env?: NodeJS.ProcessEnv | undefined;\n+  readonly registerProcess?: ((pid: number) => () => void) | undefined;\n+}\n+\n+type RunQueueItem =\n+  | { readonly _tag: \"delta\"; readonly update: InteractionUpdate }\n+  | { readonly _tag: \"done\"; readonly ok: true; readonly result: RunResult }\n+  | {\n+      readonly _tag: \"done\";\n+      readonly ok: false;\n+      readonly error: CursorAgentSdk.CursorAgentSdkRunnerError;\n+    };\n+\n+interface ActiveWorkerRun {\n+  readonly sessionId: number;\n+  readonly queue: Queue.Queue<RunQueueItem>;\n+  readonly waitDeferred: Deferred.Deferred<RunResult, CursorAgentSdk.CursorAgentSdkRunnerError>;\n+  doneEnqueued: boolean;\n+}\n+\n+function toRunnerError(method: string, cause: unknown): CursorAgentSdk.CursorAgentSdkRunnerError {\n+  return CursorAgentSdk.isCursorAgentSdkRunnerError(cause)\n+    ? cause\n+    : new CursorAgentSdk.CursorAgentSdkRunnerError({ method, cause });\n+}\n+\n+function fromSerializedFailure(\n+  failure: SerializedRunnerFailure,\n+): CursorAgentSdk.CursorAgentSdkRunnerError {\n+  return new CursorAgentSdk.CursorAgentSdkRunnerError({\n+    method: failure.method,\n+    cause: deserializeWorkerError(failure.cause),\n+  });\n+}\n+\n+function workerExitError(method: string, exitCode: number | undefined, stderr: string) {\n+  const trimmedStderr = stderr.trim();\n+  const detail = `Cursor SDK worker exited unexpectedly${exitCode === undefined ? \"\" : ` (code ${exi",
      "stagedSummary": " apps/server/package.json                           |    2 +-\n apps/server/src/binMain.ts                         |    6 +\n ...viderOrchestrationAdapterInfrastructure.test.ts |   37 +\n .../ProviderOrchestrationAdapterInfrastructure.ts  |   36 +-\n packages/provider-cursor/package.json              |   10 +-\n .../src/server/CursorAgentSdk.test.ts              |  104 +-\n .../provider-cursor/src/server/CursorAgentSdk.ts   |  235 +++-\n .../src/server/CursorAgentSdkProcessRunner.test.ts |  742 +++++++++++++\n .../src/server/CursorAgentSdkProcessRunner.ts      | 1167 ++++++++++++++++++++\n .../src/server/CursorAgentSdkWorker.ts             |  647 +++++++++++\n .../src/server/CursorAgentSdkWorkerProtocol.ts     |  304 +++++\n .../provider-cursor/src/server/adapter.test.ts     |  137 +++\n packages/provider-cursor/src/server/adapter.ts     |    3 +-\n packages/provider-cursor/src/server/driver.ts      |    1 +\n packages/provider-cursor/src/server/sdk.ts         |   42 +-\n .../src/server/textGeneration.test.ts              |   37 +\n .../provider-cursor/src/server/textGeneration.ts   |  279 +++--\n ...r__sdk@1.4.1.patch => @cursor__sdk@1.4.2.patch} |  101 +-\n pnpm-lock.yaml                                     |   58 +-\n pnpm-workspace.yaml                                |    4 +-\n 20 files changed, 3727 insertions(+), 225 deletions(-)\n"
    }
  },
  {
    "side": "before",
    "results": [
      {
        "side": "before",
        "run": 1,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825749180,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825751827,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825759307,
            "event": "run.result",
            "result": {
              "id": "run-751d6732-18a9-4a0f-b7ef-4ed928dcd88f",
              "requestId": "3fae8cca-1c39-4042-bce1-290c1fbd3d72",
              "status": "finished",
              "result": "Isolating the Cursor Agent SDK in an out-of-process worker is the main change.",
              "model": {
                "id": "default"
              },
              "durationMs": 7000,
              "usage": {
                "inputTokens": 21657,
                "outputTokens": 415,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22072,
                "reasoningTokens": 228
              }
            }
          },
          {
            "time": 1795825759307,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe commit message must be a JSON object with `subject` and `body` keys.\n\nThe primary change is moving the Cursor Agent SDK into an out-of-process worker. New files include the process runner, worker, and protocol. The server infrastructure now wires this process runner instead of using the in-process SDK.",
                        "thinkingDurationMs": 2998
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "Isolating the Cursor Agent SDK in an out-of-process worker is the main change."
                      }
                    },
                    {
                      "type": "toolCall",
                      "message": {
                        "type": "createPlan",
                        "args": {
                          "plan": "# Commit message\n\nPrimary change: run Cursor Agent SDK out of process via a `__cursor-sdk-worker` child, with process runner, protocol, shared workspace store ref-counting, and `@cursor/sdk` 1.4.2.\n\n```json\n{\n  \"subject\": \"Isolate Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, process runner, and protocol serialization\\n- Share ref-counted workspace SQLite stores with noop runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```\n"
                        },
                        "result": {
                          "status": "success",
                          "value": {}
                        }
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825759447,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825760223,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825773357,
            "event": "run.result",
            "result": {
              "id": "run-84ab934f-d4cf-44c8-afd0-0b23cdacc6c1",
              "requestId": "938e39cc-660c-43da-bdd8-d4edf1871448",
              "status": "finished",
              "result": "Primary change is isolating the Cursor Agent SDK in an out-of-process worker; drafting the commit message from that.",
              "model": {
                "id": "default"
              },
              "durationMs": 12783,
              "usage": {
                "inputTokens": 21657,
                "outputTokens": 701,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22358,
                "reasoningTokens": 506
              }
            }
          },
          {
            "time": 1795825773357,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes, and return a JSON object with keys `subject` and `body`.\n\nThis is a plan mode session, so I will only generate the commit message JSON without actually committing.\n\nThe staged changes introduce an out-of-process Cursor SDK worker. The server CLI now has a fast path for this worker. Provider orchestration switched from in-process to ProcessRunner. A shared SqliteLocalAgentStore with noop runEvents was added. The SDK bumped from 1.4.1 to 1.4.2. textGeneration was updated for the new process model.\n\nSubject: \"Run Cursor Agent SDK in an out-of-process worker\"\n\nBody bullets:\n- Process runner and NDJSON worker protocol\n- CLI `__cursor-sdk-worker` fast path\n- Shared workspace SQLite store with noop runEvents\n- SDK bump to 1.4.2\n\nI will return the JSON object directly.",
                        "thinkingDurationMs": 8083
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "Primary change is isolating the Cursor Agent SDK in an out-of-process worker; drafting the commit message from that."
                      }
                    },
                    {
                      "type": "toolCall",
                      "message": {
                        "type": "createPlan",
                        "args": {
                          "plan": "# Commit message\n\nPrimary user/developer-visible change: run the Cursor Agent SDK in a dedicated out-of-process worker (NDJSON protocol + process runner), with shared workspace SQLite store handling and `@cursor/sdk` 1.4.2.\n\n```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI path\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```\n"
                        },
                        "result": {
                          "status": "success",
                          "value": {}
                        }
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825773507,
            "event": "generation.error",
            "error": "TextGenerationError: Text generation failed in generateCommitMessage: Cursor SDK returned invalid structured output."
          }
        ],
        "success": false,
        "elapsedMs": 24371
      },
      {
        "side": "before",
        "run": 2,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825773529,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825774357,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825780564,
            "event": "run.result",
            "result": {
              "id": "run-4b8262a2-2b93-4e84-b5d9-563178792ecc",
              "requestId": "61ba8c28-f779-4fb5-a2ae-ccd43699ab57",
              "status": "finished",
              "result": "The primary change is isolating the Cursor Agent SDK in an out-of-process worker, with shared workspace SQLite and the 1.4.2 bump as supporting details.",
              "model": {
                "id": "default"
              },
              "durationMs": 5911,
              "usage": {
                "inputTokens": 21654,
                "outputTokens": 345,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 21999,
                "reasoningTokens": 192
              }
            }
          },
          {
            "time": 1795825780564,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe commit message must be a JSON object with `subject` and `body` keys.\n\nThe primary change is moving the Cursor Agent SDK out-of-process via a dedicated worker. This includes a new `CursorAgentSdkWorker`, a server CLI fast path, and switching provider orchestration to use `ProcessRunner`. The SDK version bumps from 1.4.1 to 1.4.2, and `textGenerate` support is added.",
                        "thinkingDurationMs": 3089
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "The primary change is isolating the Cursor Agent SDK in an out-of-process worker, with shared workspace SQLite and the 1.4.2 bump as supporting details."
                      }
                    },
                    {
                      "type": "toolCall",
                      "message": {
                        "type": "createPlan",
                        "args": {
                          "plan": "# Commit message\n\n```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI and NDJSON process runner\\n- Share ref-counted workspace SQLite with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```\n"
                        },
                        "result": {
                          "status": "success",
                          "value": {}
                        }
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825780697,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825781395,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825793086,
            "event": "run.result",
            "result": {
              "id": "run-212a3a57-7201-4d10-8cf6-9e8ff51d76d7",
              "requestId": "9e4bf1eb-91ca-4009-a1e1-e3bde52fe129",
              "status": "finished",
              "result": "Primary change is isolating the Cursor Agent SDK in an out-of-process worker, with shared workspace store handling as a supporting detail.",
              "model": {
                "id": "default"
              },
              "durationMs": 9662,
              "usage": {
                "inputTokens": 21654,
                "outputTokens": 634,
                "cacheReadTokens": 21632,
                "cacheWriteTokens": 0,
                "totalTokens": 22288,
                "reasoningTokens": 498
              }
            }
          },
          {
            "time": 1795825793087,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes, and return a JSON object with keys `subject` and `body`.\n\nThe primary change is running the Cursor Agent SDK out-of-process via a dedicated worker process. The commit message should capture this architectural shift.\n\nDrafting the commit message now. The subject will be imperative and under 72 characters. The body will list the process runner, NDJSON protocol, shared SQLite store, and SDK bump.\n\nI will return the JSON object directly. No plan is needed for this output-only request.",
                        "thinkingDurationMs": 6165
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "Primary change is isolating the Cursor Agent SDK in an out-of-process worker, with shared workspace store handling as a supporting detail."
                      }
                    },
                    {
                      "type": "toolCall",
                      "message": {
                        "type": "createPlan",
                        "args": {
                          "plan": "# Commit message for feature/cursor-sdk-worker staged changesSPELL```json.subject: Run Cursor Agent SDK in an out-of-process worker (\u226472, imperative, no period).body: short bullets on process runner/CLI path, shared SQLite store + noop runEvents, SDK 1.4.2 bump.```"
                        },
                        "result": {
                          "status": "success",
                          "value": {}
                        }
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825793229,
            "event": "generation.error",
            "error": "TextGenerationError: Text generation failed in generateCommitMessage: Cursor SDK returned invalid structured output."
          }
        ],
        "success": false,
        "elapsedMs": 19710
      },
      {
        "side": "before",
        "run": 3,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825793246,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825794005,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825806668,
            "event": "run.result",
            "result": {
              "id": "run-0215a2f4-fbef-4f94-a999-5abe429a9107",
              "requestId": "7180b5e9-4170-4f48-81f3-20eacd6f97a2",
              "status": "finished",
              "result": "The primary change is isolating the Cursor Agent SDK in an out-of-process worker.",
              "model": {
                "id": "default"
              },
              "durationMs": 12366,
              "usage": {
                "inputTokens": 21654,
                "outputTokens": 603,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22257,
                "reasoningTokens": 412
              }
            }
          },
          {
            "time": 1795825806668,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes.\n\nThe commit message must be a JSON object with `subject` and `body` keys.\n\nThe diff shows the Cursor Agent SDK moving to an out-of-process worker. New runner, worker, and protocol files were added. The SDK version bumped from 1.4.1 to 1.4.2. A shared SqliteLocalAgentStore with noop runEvents was introduced per workspace. ProviderOrchestrationAdapterInfrastructure and binMain were wired in.\n\nThe subject will be \"Run Cursor Agent SDK in an out-of-process worker\". The body will list the secondary changes. I will return the JSON object directly.",
                        "thinkingDurationMs": 7404
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "The primary change is isolating the Cursor Agent SDK in an out-of-process worker."
                      }
                    },
                    {
                      "type": "toolCall",
                      "message": {
                        "type": "createPlan",
                        "args": {
                          "plan": "# Commit message for Cursor SDK worker\n\nPrimary change: move Cursor Agent SDK execution into an out-of-process `__cursor-sdk-worker` with a process runner, protocol, and shared workspace SQLite store handling; bump `@cursor/sdk` to 1.4.2.\n\n```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, process runner, and protocol serialization\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```\n"
                        },
                        "result": {
                          "status": "success",
                          "value": {}
                        }
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825806813,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825807792,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825814410,
            "event": "run.result",
            "result": {
              "id": "run-46655a1e-2c14-4309-bfbe-c4c0c6ad4614",
              "requestId": "f9db7edf-5519-401e-8f6f-52b07174842d",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker protocol, process runner, and __cursor-sdk-worker CLI\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 5859,
              "usage": {
                "inputTokens": 21654,
                "outputTokens": 390,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22044,
                "reasoningTokens": 311
              }
            }
          },
          {
            "time": 1795825814410,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe commit message must be a JSON object with keys subject and body.\n\nThe changes introduce an out-of-process Cursor SDK worker via a new CLI command. New files include a process runner, worker, and protocol. Provider orchestration now uses the process runner instead of the in-process SDK. A shared SqliteLocalAgentStore with noop runEvents is added per workspace. The @cursor/sdk dependency upgrades from 1.4.1 to 1.4.2. Text generation also receives updates for out-of-process support.\n\nThe subject is \"Run Cursor agent SDK in an out-of-process worker\". The body lists the NDJSON protocol, process runner, CLI command, shared SQLite stores, and @cursor/sdk bump.",
                        "thinkingDurationMs": 3621
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker protocol, process runner, and __cursor-sdk-worker CLI\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825815304,
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker protocol, process runner, and __cursor-sdk-worker CLI\n- Share ref-counted workspace SQLite stores with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 22066
      },
      {
        "side": "before",
        "run": 4,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825815331,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825817194,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825828556,
            "event": "run.result",
            "result": {
              "id": "run-eec83794-000c-4cfa-95bc-ab055af8eb65",
              "requestId": "765af08f-a691-4128-9f14-23359404bef4",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Isolate Cursor agent SDK behind an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI path\\n- Share ref-counted workspace SQLite stores with noop runEvents writes\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 11031,
              "usage": {
                "inputTokens": 21660,
                "outputTokens": 443,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22103,
                "reasoningTokens": 363
              }
            }
          },
          {
            "time": 1795825828557,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe commit message must be a JSON object with keys subject and body.\n\nThe primary change is moving the Cursor agent SDK out-of-process via a new worker. This isolates it from the main server process. Provider orchestration now uses a process runner instead of the in-process SDK. The server also wires this through a `__cursor-sdk-worker` CLI fast path. A shared SqliteLocalAgentStore with ref-counting and noop runEvents was added per workspace. The @cursor/sdk dependency was bumped to 1.4.2. Tests were added for all of these changes.",
                        "thinkingDurationMs": 7708
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Isolate Cursor agent SDK behind an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI path\\n- Share ref-counted workspace SQLite stores with noop runEvents writes\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825828714,
            "event": "generation.success",
            "result": {
              "subject": "Isolate Cursor agent SDK behind an out-of-process worker",
              "body": "- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI path\n- Share ref-counted workspace SQLite stores with noop runEvents writes\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 13401
      },
      {
        "side": "before",
        "run": 5,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825828751,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825829471,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825837687,
            "event": "run.result",
            "result": {
              "id": "run-d5d6e5da-511e-4c5f-a0c1-7de7793d2234",
              "requestId": "d1281a42-1d8e-4410-bc44-999d36e7ae29",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI path\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 7937,
              "usage": {
                "inputTokens": 21660,
                "outputTokens": 352,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22012,
                "reasoningTokens": 271
              }
            }
          },
          {
            "time": 1795825837688,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nThe commit message must be a JSON object with subject and body keys.\n\nThe staged changes isolate the Cursor Agent SDK in an out-of-process worker. The server wires this via a `__cursor-sdk-worker` CLI fast path. Provider orchestration now uses a process runner instead of the in-process agent. A shared ref-counted SqliteLocalAgentStore per workspace replaces the old in-process store. The @cursor/sdk dependency bumps from 1.4.1 to 1.4.2. Tests cover all of these changes.\n\nThe subject will be \"Run Cursor Agent SDK in an out-of-process worker\". I will return the JSON object directly without creating a plan.",
                        "thinkingDurationMs": 5088
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI path\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825837831,
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI path\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 9099
      },
      {
        "side": "before",
        "run": 6,
        "sha": "13f9213cffc08ecc6d4ee434aae4cd0bbc76fd93",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825837864,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825838739,
            "event": "Agent.create",
            "mode": "plan",
            "tools": "SDK defaults",
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825847500,
            "event": "run.result",
            "result": {
              "id": "run-5aa0c629-b3f9-4dc3-9f32-cb39ac90d904",
              "requestId": "9fadc6a1-3dff-432e-bf43-feb965c3867e",
              "status": "finished",
              "result": "Primary change is isolating the Cursor Agent SDK behind an out-of-process worker.\n\n```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 8456,
              "usage": {
                "inputTokens": 21660,
                "outputTokens": 357,
                "cacheReadTokens": 4864,
                "cacheWriteTokens": 0,
                "totalTokens": 22017,
                "reasoningTokens": 267
              }
            }
          },
          {
            "time": 1795825847500,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes.\n\nThe commit message must be a JSON object with keys `subject` and `body`.\n\nThe primary change is running the Cursor Agent SDK out-of-process via a new worker process. The commit message should capture this core shift.\n\nDrafting the JSON commit message now. The subject will be imperative and under 72 characters, with a short body capturing the key changes.",
                        "thinkingDurationMs": 5661
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "Primary change is isolating the Cursor Agent SDK behind an out-of-process worker.\n\n```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825847656,
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker CLI, protocol, and process runner\n- Share ref-counted workspace SQLite stores with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 9810
      }
    ],
    "input": {
      "stagedPatch": "diff --git a/apps/server/package.json b/apps/server/package.json\nindex e9f211891a..8ece0aaa81 100644\n--- a/apps/server/package.json\n+++ b/apps/server/package.json\n@@ -37,7 +37,7 @@\n   },\n   \"dependencies\": {\n     \"@anthropic-ai/claude-agent-sdk\": \"^0.3.321\",\n-    \"@cursor/sdk\": \"1.4.1\",\n+    \"@cursor/sdk\": \"1.4.2\",\n     \"@effect/platform-node\": \"catalog:\",\n     \"@effect/platform-node-shared\": \"catalog:\",\n     \"@ff-labs/fff-node\": \"0.11.0\",\ndiff --git a/apps/server/src/binMain.ts b/apps/server/src/binMain.ts\nindex 0dabd73873..7d4c93fb04 100644\n--- a/apps/server/src/binMain.ts\n+++ b/apps/server/src/binMain.ts\n@@ -30,6 +30,12 @@ export async function runCliCommand() {\n     if (mode !== \"discover\" && mode !== \"model\") throw new Error(\"Unknown speech worker mode.\");\n     const { runNativeSpeechWorker } = await import(\"./speech/native.ts\");\n     await runNativeSpeechWorker(mode, process.argv[4]);\n+  } else if (command === \"__cursor-sdk-worker\") {\n+    const [NodeServices, { runCursorSdkWorker }] = await Promise.all([\n+      import(\"@effect/platform-node/NodeServices\"),\n+      import(\"@t3tools/provider-cursor/server/worker\"),\n+    ]);\n+    await runCursorSdkWorker(NodeServices.layer);\n   } else {\n     enableCliCompileCache();\n     // Windows desktop launches without stdin; attach before reading, except on fast paths using pipes.\ndiff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\nindex 8458b46b30..981f6847ef 100644\n--- a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\n+++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\n@@ -1,8 +1,14 @@\n+import * as NodeServices from \"@effect/platform-node/NodeServices\";\n import { assert, it } from \"@effect/vitest\";\n import { ProviderDriverKind } from \"@t3tools/contracts\";\n import * as IdAllocator from \"@t3tools/provider-core/server/IdAllocator\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n import * as Effect from \"effect/Effect\";\n import * as Layer from \"effect/Layer\";\n+import * as Path from \"effect/Path\";\n+import * as ChildProcess from \"effect/process/ChildProcess\";\n+import * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\n+import * as Stream from \"effect/Stream\";\n import * as SqlClient from \"effect/sql/SqlClient\";\n \n import * as SqlitePersistence from \"../persistence/Sqlite.ts\";\n@@ -40,3 +46,34 @@ it.effect(\"subagent threads stored under a legacy id keep it when re-derived\", (\n     );\n   }),\n );\n+\n+it.live(\"spawns the __cursor-sdk-worker CLI fast path and shuts down cleanly on close\", () =>\n+  Effect.scoped(\n+    Effect.gen(function* () {\n+      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n+      const path = yield* Path.Path;\n+      const executable = yield* HostProcess.ExecutablePath;\n+      const entry = yield* path.fromFileUrl(new URL(\"../bin.ts\", import.meta.url));\n+      const handle = yield* spawner.spawn(\n+        ChildProcess.make(executable, [entry, \"__cursor-sdk-worker\"], {\n+          stdin: { stream: \"pipe\", endOnDone: false },\n+          stdout: \"pipe\",\n+          stderr: \"pipe\",\n+        }),\n+      );\n+      yield* Stream.run(\n+        Stream.encodeText(Stream.make(`${JSON.stringify({ id: 1, type: \"close\" })}\\n`)),\n+        handle.stdin,\n+      );\n+      const stdout = yield* handle.stdout.pipe(Stream.decodeText(), Stream.mkString);\n+      const exitCode = Number(yield* handle.exitCode);\n+      assert.strictEqual(exitCode, 0);\n+      assert.deepStrictEqual(JSON.parse(stdout.trim()), {\n+        type: \"response\",\n+        id: 1,\n+        ok: true,\n+        result: null,\n+      });\n+    }),\n+  ).pipe(Effect.provide(NodeServices.layer)),\n+);\ndiff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\nindex b01735a7c2..ffb25e7daa 100644\n--- a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\n+++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\n@@ -1,13 +1,17 @@\n import * as Effect from \"effect/Effect\";\n import * as Layer from \"effect/Layer\";\n+import * as Path from \"effect/Path\";\n import * as SqlClient from \"effect/sql/SqlClient\";\n \n import * as ClaudeAdapterV2 from \"../orchestration-v2/Adapters/ClaudeAdapterV2.ts\";\n import * as CodexAdapterV2 from \"../orchestration-v2/Adapters/CodexAdapterV2.ts\";\n-import * as CursorAgentSdk from \"@t3tools/provider-cursor/server/CursorAgentSdk\";\n+import * as ProviderProcesses from \"../process/providerProcesses.ts\";\n+import type * as CursorAgentSdk from \"@t3tools/provider-cursor/server/CursorAgentSdk\";\n+import * as CursorAgentSdkProcessRunner from \"@t3tools/provider-cursor/server/CursorAgentSdkProcessRunner\";\n import * as CursorSdk from \"@t3tools/provider-cursor/server/CursorSdk\";\n import * as IdAllocator from \"@t3tools/provider-core/server/IdAllocator\";\n import * as ProviderContinuationRequests from \"@t3tools/provider-core/server/ProviderContinuationRequests\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n \n export type ProviderOrchestrationAdapterInfrastructure =\n   | ClaudeAdapterV2.ClaudeAgentSdkQueryRunner\n@@ -34,11 +38,39 @@ export const layerIdAllocator = Layer.unwrap(\n   }),\n );\n \n+const resolveCursorWorkerLaunch = Effect.gen(function* () {\n+  const path = yield* Path.Path;\n+  const command = yield* HostProcess.ExecutablePath;\n+  const isExecutable = yield* HostProcess.IsExecutable;\n+  const providerProcesses = yield* ProviderProcesses.ProviderProcesses;\n+  // In a bundle import.meta.url is bin.mjs; development and tests use this source module.\n+  const entry = yield* path\n+    .fromFileUrl(\n+      new URL(import.meta.url.endsWith(\".ts\") ? \"../bin.ts\" : \"./bin.mjs\", import.meta.url),\n+    )\n+    .pipe(Effect.orDie);\n+  return {\n+    command,\n+    args: [...(isExecutable ? [] : [entry]), \"__cursor-sdk-worker\"],\n+    ...(providerProcesses.register === undefined\n+      ? {}\n+      : { registerProcess: providerProcesses.register }),\n+  };\n+});\n+\n /** Reuse the continuation worker's exact layer reference so memoization shares one queue. */\n export const layer = Layer.mergeAll(\n   ClaudeAdapterV2.layerQueryRunner,\n   CodexAdapterV2.layerAppServerClientFactory,\n-  CursorAgentSdk.layer.pipe(Layer.provideMerge(CursorSdk.layer)),\n+  Layer.unwrap(\n+    Effect.gen(function* () {\n+      const path = yield* Path.Path;\n+      return CursorAgentSdkProcessRunner.layer(\n+        resolveCursorWorkerLaunch.pipe(Effect.provideService(Path.Path, path)),\n+      );\n+    }),\n+  ),\n+  CursorSdk.layer,\n   layerIdAllocator,\n   ProviderContinuationRequests.layer,\n );\ndiff --git a/packages/provider-cursor/package.json b/packages/provider-cursor/package.json\nindex e1d101a92f..dcd6bd0904 100644\n--- a/packages/provider-cursor/package.json\n+++ b/packages/provider-cursor/package.json\n@@ -23,6 +23,14 @@\n       \"types\": \"./src/server/CursorAgentSdk.ts\",\n       \"import\": \"./src/server/CursorAgentSdk.ts\"\n     },\n+    \"./server/CursorAgentSdkProcessRunner\": {\n+      \"types\": \"./src/server/CursorAgentSdkProcessRunner.ts\",\n+      \"import\": \"./src/server/CursorAgentSdkProcessRunner.ts\"\n+    },\n+    \"./server/worker\": {\n+      \"types\": \"./src/server/CursorAgentSdkWorker.ts\",\n+      \"import\": \"./src/server/CursorAgentSdkWorker.ts\"\n+    },\n     \"./server/accountUsage\": {\n       \"types\": \"./src/server/accountUsage.ts\",\n       \"import\": \"./src/server/accountUsage.ts\"\n@@ -45,7 +53,7 @@\n     \"test\": \"vp test run --config ../../vite.config.ts --dir .\"\n   },\n   \"dependencies\": {\n-    \"@cursor/sdk\": \"1.4.1\",\n+    \"@cursor/sdk\": \"1.4.2\",\n     \"@t3tools/contracts\": \"workspace:*\",\n     \"@t3tools/provider-core\": \"workspace:*\",\n     \"@t3tools/shared\": \"workspace:*\",\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\nindex 187ce35990..94ae520513 100644\n--- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\n+++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\n@@ -60,7 +60,7 @@ const cursorSdkMock = vi.hoisted(() => {\n       };\n     },\n   );\n-  const create = vi.fn(async () => ({\n+  const create = vi.fn(async (_options?: unknown) => ({\n     agentId: \"agent-cursor-agent-sdk-test\",\n     send,\n     close: agentClose,\n@@ -87,6 +87,8 @@ const cursorSdkMock = vi.hoisted(() => {\n     );\n   });\n \n+  const sqliteOpen = vi.fn<() => Promise<unknown>>(async () => undefined);\n+\n   return {\n     agentClose,\n     cancelRun,\n@@ -99,6 +101,7 @@ const cursorSdkMock = vi.hoisted(() => {\n     runSteer,\n     runWait,\n     send,\n+    sqliteOpen,\n     setAgentCloseFailure: (failure: unknown) => {\n       agentCloseFailure = failure;\n     },\n@@ -121,7 +124,7 @@ vi.mock(\"./sdk.ts\", () => ({\n     },\n     createAgentPlatform: vi.fn(),\n   }),\n-  loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: vi.fn() } }),\n+  loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: cursorSdkMock.sqliteOpen } }),\n }));\n \n const layerTest = CursorAgentSdk.layer.pipe(\n@@ -509,4 +512,101 @@ describe(\"CursorAgentSdkRunner\", () => {\n       assert.equal(yield* plain.steer!(\"later\"), \"revert_to_followup\");\n     }).pipe(Effect.provide(layerTest)),\n   );\n+\n+  it.effect(\n+    \"ref-counts one disposable SqliteLocalAgentStore with no-op runEvents per workspace\",\n+    () =>\n+      Effect.gen(function* () {\n+        const dispose = vi.fn(async () => {});\n+        const underlyingAppend = vi.fn(async () => {\n+          throw new Error(\"runEvents.append must not hit SQLite\");\n+        });\n+        const fakeStore = {\n+          agents: { get: vi.fn() },\n+          runs: { list: vi.fn() },\n+          checkpoints: { save: vi.fn() },\n+          runEvents: { append: underlyingAppend, list: vi.fn(), delete: vi.fn() },\n+          dispose,\n+        };\n+        cursorSdkMock.sqliteOpen.mockClear();\n+        cursorSdkMock.sqliteOpen.mockResolvedValueOnce(fakeStore);\n+        cursorSdkMock.create.mockClear();\n+\n+        const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;\n+        const session = yield* runner.open({\n+          operation: \"create\",\n+          options: { local: { cwd: \"/workspace/cursor-store-test\" } },\n+          threadId: ThreadId.make(\"thread-cursor-agent-sdk-store\"),\n+          providerSessionId: ProviderSessionId.make(\"provider-session-cursor-agent-sdk-store\"),\n+        });\n+        const peer = yield* runner.open({\n+          operation: \"create\",\n+          options: { local: { cwd: \"/workspace/cursor-store-test\" } },\n+          threadId: ThreadId.make(\"thread-cursor-agent-sdk-store-peer\"),\n+          providerSessionId: ProviderSessionId.make(\"provider-session-cursor-agent-sdk-store-peer\"),\n+        });\n+\n+        assert.deepStrictEqual(cursorSdkMock.sqliteOpen.mock.calls, [\n+          [{ workspaceRef: \"/workspace/cursor-store-test\" }],\n+        ]);\n+        const passedOptions = cursorSdkMock.create.mock.calls[0]?.[0] as\n+          | {\n+              readonly local?: {\n+                readonly store?: {\n+                  readonly agents: unknown;\n+                  readonly checkpoints: unknown;\n+                  readonly runEvents: {\n+                    readonly append: (event: {\n+                      readonly runId: string;\n+                      readonly eventType: string;\n+                      readonly payload?: unknown;\n+                    }) => Promise<{ readonly seq: number }>;\n+                  };\n+                };\n+              };\n+            }\n+          | undefined;\n+        const peerOptions = cursorSdkMock.create.mock.calls[1]?.[0] as typeof passedOptions;\n+        const passedStore = passedOptions?.local?.store;\n+        assert.isDefined(passedStore);\n+        assert.strictEqual(peerOptions?.local?.store, passedStore);\n+        assert.strictEqual(passedStore?.agents, fakeStore.agents);\n+        assert.strictEqual(passedStore?.checkpoints, fakeStore.checkpoints);\n+        const appended = yield* Effect.promise(() =>\n+          passedStore!.runEvents.append({\n+            runId: \"run-1\",\n+            eventType: \"text-delta\",\n+            payload: { text: \"hi\" },\n+          }),\n+        );\n+        assert.equal(appended.seq, 1);\n+        assert.equal(underlyingAppend.mock.calls.length, 0);\n+        assert.equal(dispose.mock.calls.length, 0);\n+\n+        // Closing one session keeps the shared workspace store alive; repeated close does not double-release.\n+        yield* session.close;\n+        yield* session.close;\n+        assert.equal(dispose.mock.calls.length, 0);\n+\n+        yield* peer.close;\n+        assert.equal(dispose.mock.calls.length, 1);\n+\n+        // Failed open disposes the newly opened store instead of leaking SQLite FDs.\n+        const failingDispose = vi.fn(async () => {});\n+        cursorSdkMock.sqliteOpen.mockResolvedValueOnce({ ...fakeStore, dispose: failingDispose });\n+        cursorSdkMock.create.mockRejectedValueOnce(new Error(\"boom\"));\n+        const failed = yield* runner\n+          .open({\n+            operation: \"create\",\n+            options: { local: { cwd: \"/workspace/cursor-store-fail\" } },\n+            threadId: ThreadId.make(\"thread-cursor-agent-sdk-store-fail\"),\n+            providerSessionId: ProviderSessionId.make(\n+              \"provider-session-cursor-agent-sdk-store-fail\",\n+            ),\n+          })\n+          .pipe(Effect.exit);\n+        assert(Exit.isFailure(failed));\n+        assert.equal(failingDispose.mock.calls.length, 1);\n+      }).pipe(Effect.provide(layerTest)),\n+  );\n });\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts\nindex 75b0232ebf..81b8208a5d 100644\n--- a/packages/provider-cursor/src/server/CursorAgentSdk.ts\n+++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts\n@@ -18,10 +18,12 @@ import {\n import * as Context from \"effect/Context\";\n import * as Deferred from \"effect/Deferred\";\n import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n import * as Layer from \"effect/Layer\";\n import * as Option from \"effect/Option\";\n import * as Ref from \"effect/Ref\";\n import * as Schema from \"effect/Schema\";\n+import * as Semaphore from \"effect/Semaphore\";\n \n import * as CursorSdk from \"./CursorSdk.ts\";\n import * as ProviderEventLoggers from \"@t3tools/provider-core/server/ProviderEventLoggers\";\n@@ -165,9 +167,19 @@ export interface CursorAgentSdkSession {\n    * The open agent keeps its old conversation in memory, so reopen it before the next send.\n    */\n   readonly rewindAfterRun?: (runId: string) => Effect.Effect<void, CursorAgentSdkRunnerError>;\n+  /** False once an out-of-process worker has terminated or started closing; absent on in-process sessions. */\n+  readonly isAlive?: () => boolean;\n   readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;\n }\n \n+export interface CursorAgentSdkTextGenerateInput {\n+  readonly prompt: string;\n+  readonly apiKey: string;\n+  readonly model: NonNullable<AgentOptions[\"model\"]>;\n+  readonly cwd: string;\n+  readonly stateRoot: string;\n+}\n+\n export class CursorAgentSdkRunner extends Context.Service<\n   CursorAgentSdkRunner,\n   {\n@@ -175,6 +187,10 @@ export class CursorAgentSdkRunner extends Context.Service<\n       input: CursorAgentSdkOpenInput,\n     ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;\n     readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;\n+    /** Absent on in-process test doubles; the out-of-process runner provides it. */\n+    readonly textGenerate?: (\n+      input: CursorAgentSdkTextGenerateInput,\n+    ) => Effect.Effect<RunResult, CursorAgentSdkRunnerError>;\n   }\n >()(\"@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner\") {}\n \n@@ -414,7 +430,7 @@ export function loggedCursorSendOptions(\n   };\n }\n \n-function makeCursorAgentSdkProtocolLogger(input: {\n+export function makeCursorAgentSdkProtocolLogger(input: {\n   readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;\n   readonly threadId: ThreadId;\n   readonly providerSessionId: OrchestrationV2ProviderSession[\"id\"];\n@@ -463,6 +479,60 @@ function subscribeShellStreamOutput(listener: (output: CursorShellStreamOutput)\n   };\n }\n \n+type CursorLocalStore = NonNullable<NonNullable<AgentOptions[\"local\"]>[\"store\"]>;\n+\n+interface DisposableCursorLocalStore extends CursorLocalStore {\n+  readonly dispose: () => Promise<void>;\n+}\n+\n+function isDisposableCursorLocalStore(value: unknown): value is DisposableCursorLocalStore {\n+  return (\n+    typeof value === \"object\" &&\n+    value !== null &&\n+    \"agents\" in value &&\n+    \"runs\" in value &&\n+    \"checkpoints\" in value &&\n+    \"runEvents\" in value &&\n+    \"dispose\" in value &&\n+    typeof value.dispose === \"function\"\n+  );\n+}\n+\n+// T3 persists its own event log and never tails SDK run_events; skipping per-delta SQLite\n+// run_events writes avoids synchronous BEGIN IMMEDIATE write locks and multi-GB index.db bloat.\n+export function withNoopCursorRunEvents(store: CursorLocalStore): CursorLocalStore {\n+  if (\n+    typeof store !== \"object\" ||\n+    store === null ||\n+    typeof store.runEvents?.append !== \"function\"\n+  ) {\n+    return store;\n+  }\n+  let seq = 0;\n+  return {\n+    agents: store.agents,\n+    runs: store.runs,\n+    checkpoints: store.checkpoints,\n+    runEvents: {\n+      append: async (event) => {\n+        seq += 1;\n+        return {\n+          runId: event.runId,\n+          seq,\n+          offset: String(seq),\n+          eventType: event.eventType,\n+          payload: event.payload ?? null,\n+          payloadRef: event.payloadRef ?? null,\n+          idempotencyKey: event.idempotencyKey ?? null,\n+          createdAt: 0,\n+        };\n+      },\n+      list: async () => ({ items: [] }),\n+      delete: async () => {},\n+    },\n+  };\n+}\n+\n interface CursorBackgroundShell {\n   readonly conversationId?: unknown;\n   readonly command?: unknown;\n@@ -548,6 +618,58 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n     },\n   );\n \n+  // Ref-count one SqliteLocalAgentStore per workspace so concurrent sessions share a single\n+  // index.db handle while still disposing handles, page caches, and FDs once the last one closes.\n+  interface WorkspaceStoreLease {\n+    readonly store: DisposableCursorLocalStore;\n+    readonly wrapped: CursorLocalStore;\n+    users: number;\n+  }\n+  const workspaceStores = new Map<string, WorkspaceStoreLease>();\n+  const workspaceStoreLock = yield* Semaphore.make(1);\n+  const acquireWorkspaceStore = (workspaceRef: string, method: string) =>\n+    workspaceStoreLock.withPermits(1)(\n+      Effect.suspend(() => {\n+        const existing = workspaceStores.get(workspaceRef);\n+        if (existing !== undefined) {\n+          existing.users += 1;\n+          return Effect.succeed(existing);\n+        }\n+        return Effect.tryPromise({\n+          try: async () => {\n+            const candidate = await sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef });\n+            return isDisposableCursorLocalStore(candidate) ? candidate : undefined;\n+          },\n+          catch: (cause) => runnerError(cause, method),\n+        }).pipe(\n+          Effect.map((opened) => {\n+            if (opened === undefined) return undefined;\n+            const lease: WorkspaceStoreLease = {\n+              store: opened,\n+              wrapped: withNoopCursorRunEvents(opened),\n+              users: 1,\n+            };\n+            workspaceStores.set(workspaceRef, lease);\n+            return lease;\n+          }),\n+        );\n+      }),\n+    );\n+  const releaseWorkspaceStore = (workspaceRef: string, lease: WorkspaceStoreLease) =>\n+    workspaceStoreLock.withPermits(1)(\n+      Effect.suspend(() => {\n+        lease.users -= 1;\n+        if (lease.users > 0) return Effect.void;\n+        if (workspaceStores.get(workspaceRef) === lease) {\n+          workspaceStores.delete(workspaceRef);\n+        }\n+        return Effect.tryPromise({\n+          try: () => lease.store.dispose(),\n+          catch: () => undefined,\n+        }).pipe(Effect.ignore);\n+      }),\n+    );\n+\n   return CursorAgentSdkRunner.of({\n     open: Effect.fn(\"CursorAgentSdkRunner.open\")(function* (input) {\n       const { Agent, createAgentPlatform } = yield* Effect.try({\n@@ -573,59 +695,85 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n       });\n \n       // Cursor uses cwd for both execution and store lookup; a moved thread keeps its original store.\n-      const storeCwd = input.storeCwd;\n-      const storePlatform =\n-        input.operation === \"resume\" &&\n-        storeCwd !== undefined &&\n-        storeCwd !== input.options.local?.cwd\n-          ? yield* Effect.tryPromise({\n-              try: () =>\n-                createAgentPlatform({\n-                  workspaceRef: storeCwd,\n-                  ...(input.options.local?.store === undefined\n-                    ? {}\n-                    : { localStore: input.options.local.store }),\n-                }),\n-              catch: (cause) => runnerError(cause, \"agent.resume\"),\n-            })\n-          : undefined;\n-      const agent = yield* Effect.tryPromise({\n-        try: () =>\n-          input.operation === \"create\"\n-            ? Agent.create(input.options)\n-            : storePlatform === undefined\n-              ? Agent.resume(input.agentId!, input.options)\n-              : storePlatform.resumeAgent(input.agentId!, input.options),\n-        catch: (cause) => runnerError(cause, `agent.${input.operation}`),\n-      });\n-      let shellListener: ((event: CursorBackgroundShellEvent) => void) | undefined;\n-\n-      yield* log({\n-        direction: \"incoming\",\n-        stage: \"decoded\",\n-        payload: {\n-          type: \"agent.opened\",\n-          agentId: agent.agentId,\n-        },\n-      });\n-\n       const cwd =\n         typeof input.options.local?.cwd === \"string\"\n           ? input.options.local.cwd\n           : input.options.local?.cwd?.[0];\n+      const storeCwd = input.storeCwd;\n+      const storeWorkspace =\n+        input.operation === \"resume\" && storeCwd !== undefined ? storeCwd : cwd;\n+      const ownedStoreLease =\n+        input.options.local?.store === undefined && storeWorkspace !== undefined\n+          ? yield* acquireWorkspaceStore(storeWorkspace, `agent.${input.operation}`)\n+          : undefined;\n+      let storeReleased = false;\n+      const disposeOwnedStore =\n+        ownedStoreLease === undefined || storeWorkspace === undefined\n+          ? Effect.void\n+          : Effect.suspend(() => {\n+              if (storeReleased) return Effect.void;\n+              storeReleased = true;\n+              return releaseWorkspaceStore(storeWorkspace, ownedStoreLease);\n+            });\n+      const effectiveStore =\n+        ownedStoreLease === undefined ? input.options.local?.store : ownedStoreLease.wrapped;\n+      const effectiveOptions: AgentOptions =\n+        effectiveStore === undefined || effectiveStore === input.options.local?.store\n+          ? input.options\n+          : {\n+              ...input.options,\n+              local: {\n+                ...input.options.local,\n+                store: effectiveStore,\n+              },\n+            };\n+\n+      const { storePlatform, agent } = yield* Effect.gen(function* () {\n+        const resolvedStorePlatform =\n+          input.operation === \"resume\" &&\n+          storeCwd !== undefined &&\n+          storeCwd !== input.options.local?.cwd\n+            ? yield* Effect.tryPromise({\n+                try: () =>\n+                  createAgentPlatform({\n+                    workspaceRef: storeCwd,\n+                    ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),\n+                  }),\n+                catch: (cause) => runnerError(cause, \"agent.resume\"),\n+              })\n+            : undefined;\n+        const openedAgent = yield* Effect.tryPromise({\n+          try: () =>\n+            input.operation === \"create\"\n+              ? Agent.create(effectiveOptions)\n+              : resolvedStorePlatform === undefined\n+                ? Agent.resume(input.agentId!, effectiveOptions)\n+                : resolvedStorePlatform.resumeAgent(input.agentId!, effectiveOptions),\n+          catch: (cause) => runnerError(cause, `agent.${input.operation}`),\n+        });\n+        yield* log({\n+          direction: \"incoming\",\n+          stage: \"decoded\",\n+          payload: {\n+            type: \"agent.opened\",\n+            agentId: openedAgent.agentId,\n+          },\n+        });\n+        return { storePlatform: resolvedStorePlatform, agent: openedAgent };\n+      }).pipe(Effect.onExit((exit) => (Exit.isFailure(exit) ? disposeOwnedStore : Effect.void)));\n+      let shellListener: ((event: CursorBackgroundShellEvent) => void) | undefined;\n+\n       const runOptions = {\n         runtime: \"local\" as const,\n         ...(cwd === undefined ? {} : { cwd }),\n-        ...(input.options.local?.store === undefined ? {} : { store: input.options.local.store }),\n+        ...(effectiveStore === undefined ? {} : { store: effectiveStore }),\n       };\n       let abandonedRunRecoveryAvailable = input.operation === \"resume\";\n       const storeView = async () =>\n         storePlatform ??\n         (await createAgentPlatform({\n           ...(cwd === undefined ? {} : { workspaceRef: cwd }),\n-          ...(input.options.local?.store === undefined\n-            ? {}\n-            : { localStore: input.options.local.store }),\n+          ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),\n         }));\n \n       return {\n@@ -879,9 +1027,7 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n                   ? Agent.messages.list(agent.agentId, {\n                       runtime: \"local\",\n                       ...(cwd === undefined ? {} : { cwd }),\n-                      ...(input.options.local?.store === undefined\n-                        ? {}\n-                        : { store: input.options.local.store }),\n+                      ...(effectiveStore === undefined ? {} : { store: effectiveStore }),\n                     })\n                   : storePlatform.getAgentMessages(agent.agentId),\n               catch: (cause) => runnerError(cause, \"agent.messages.list\"),\n@@ -1010,6 +1156,7 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n               catch: (cause) => runnerError(cause, \"agent.close\"),\n             }),\n           ),\n+          Effect.ensuring(disposeOwnedStore),\n         ),\n       } satisfies CursorAgentSdkSession;\n     }),\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts\nnew file mode 100644\nindex 0000000000..430907b101\n--- /dev/null\n+++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts\n@@ -0,0 +1,742 @@\n+import * as NodeServices from \"@effect/platform-node/NodeServices\";\n+import { assert, describe, it } from \"@effect/vitest\";\n+import { ProviderSessionId, ThreadId } from \"@t3tools/contracts\";\n+import { AgentScope } from \"@t3tools/shared/AgentScope\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n+import * as Deferred from \"effect/Deferred\";\n+import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n+import * as Fiber from \"effect/Fiber\";\n+import * as FileSystem from \"effect/FileSystem\";\n+import * as Path from \"effect/Path\";\n+\n+import * as CursorAgentSdk from \"./CursorAgentSdk.ts\";\n+import * as CursorAgentSdkProcessRunner from \"./CursorAgentSdkProcessRunner.ts\";\n+import {\n+  deserializeRunResult,\n+  deserializeWorkerError,\n+  serializeRunResult,\n+  serializeWorkerError,\n+} from \"./CursorAgentSdkWorkerProtocol.ts\";\n+import { isCursorSdkError, tagCursorSdkError } from \"./sdk.ts\";\n+\n+// Minimal fake worker script implementing the NDJSON worker protocol in a real child Node process.\n+const FAKE_WORKER_SCRIPT = `\n+const readline = require(\"node:readline\");\n+const rawWrite = process.stdout.write.bind(process.stdout);\n+const send = (msg) => rawWrite(JSON.stringify(msg) + \"\\\\n\");\n+const mode = process.env.FAKE_WORKER_MODE || \"ok\";\n+\n+const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });\n+rl.on(\"line\", (line) => {\n+  if (!line.trim()) return;\n+  const req = JSON.parse(line);\n+  if (req.type === \"open\") {\n+    if (mode === \"config-error\") {\n+      send({\n+        type: \"response\",\n+        id: req.id,\n+        ok: false,\n+        error: {\n+          method: \"agent.create\",\n+          cause: {\n+            name: \"ConfigurationError\",\n+            message: \"Cannot use this model: bad-model\",\n+            sdkErrorKind: \"ConfigurationError\",\n+          },\n+        },\n+      });\n+      return;\n+    }\n+    rawWrite(\"non-json noise that must be ignored\\\\n\");\n+    send({ type: \"response\", id: req.id, ok: true, result: { agentId: \"agent-worker-1\" } });\n+    return;\n+  }\n+  if (req.type === \"send\") {\n+    if (mode === \"hang-send\") {\n+      send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.started\", runId: \"pending\", agentId: \"agent-worker-1\" } } });\n+      return;\n+    }\n+    if (mode === \"crash-mid-run\") {\n+      send({ type: \"response\", id: req.id, ok: true, result: { runId: \"run-crash\", agentId: \"agent-worker-1\" } });\n+      process.stderr.write(\"fatal worker boom\\\\n\");\n+      process.exit(17);\n+      return;\n+    }\n+    // Emit an early delta before the send response to verify parent buffering/ordering.\n+    send({ type: \"delta\", sendId: req.id, update: { type: \"text-delta\", text: \"early-\" } });\n+    send({ type: \"response\", id: req.id, ok: true, result: { runId: \"run-worker-1\", agentId: \"agent-worker-1\" } });\n+    if (mode === \"cancel\") {\n+      return;\n+    }\n+    send({ type: \"delta\", sendId: req.id, update: { type: \"text-delta\", text: \"late\" } });\n+    send({\n+      type: \"runDone\",\n+      sendId: req.id,\n+      ok: true,\n+      result: {\n+        id: \"run-worker-1\",\n+        requestId: \"req-1\",\n+        status: \"finished\",\n+        result: \"early-late\",\n+        model: { id: \"default\" },\n+        durationMs: 5,\n+      },\n+    });\n+    if (mode === \"exit-after-done\") {\n+      rawWrite(\"\", () => process.exit(0));\n+    }\n+    if (mode === \"background-shell\" && req.listenBackgroundShells) {\n+      send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"started\", id: \"sh-1\", pid: 4101, command: \"sleep 60\" } });\n+      send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"started\", id: \"sh-2\", pid: 4102, command: \"tail -f\" } });\n+    }\n+    return;\n+  }\n+  if (req.type === \"stopBackgroundShell\") {\n+    send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"ended\", id: req.shellId, pid: 4101, command: \"sleep 60\", stopped: true, exitCode: undefined, outputPath: undefined } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    if (mode === \"background-shell\") {\n+      rawWrite(\"\", () => process.exit(19));\n+    }\n+    return;\n+  }\n+  if (req.type === \"steer\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: \"complete_delivered\" });\n+    return;\n+  }\n+  if (req.type === \"cancel\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.cancel\", runId: \"run-worker-1\" } } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    send({\n+      type: \"runDone\",\n+      sendId: req.sendId,\n+      ok: true,\n+      result: {\n+        id: \"run-worker-1\",\n+        requestId: \"req-1\",\n+        status: \"cancelled\",\n+        model: { id: \"default\" },\n+        durationMs: 2,\n+      },\n+    });\n+    return;\n+  }\n+  if (req.type === \"listMessages\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: [{ id: \"m1\", role: \"assistant\", text: \"early-late\" }] });\n+    return;\n+  }\n+  if (req.type === \"readContextUsage\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: { usedTokens: 120, maxTokens: 1000 } });\n+    return;\n+  }\n+  if (req.type === \"runCheckpointed\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: req.runId === \"run-worker-1\" });\n+    return;\n+  }\n+  if (req.type === \"rewindAfterRun\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"textGenerate\" && mode === \"hang-text\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.started\", runId: \"text\", agentId: \"text\" } } });\n+    return;\n+  }\n+  if (req.type === \"cancelTextGenerate\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.cancel\", runId: \"text\" } } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"textGenerate\") {\n+    if (mode === \"rate-limit-text\") {\n+      send({\n+        type: \"response\",\n+        id: req.id,\n+        ok: true,\n+        result: {\n+          id: \"run-tg-1\",\n+          requestId: \"req-tg-1\",\n+          status: \"error\",\n+          model: { id: \"default\" },\n+          durationMs: 3,\n+          error: {\n+            name: \"RateLimitError\",\n+            message: \"Too many requests\",\n+            code: \"PRO_USER_USAGE_LIMIT\",\n+            status: 429,\n+            sdkErrorKind: \"CursorSdkError\",\n+          },\n+        },\n+      });\n+      return;\n+    }\n+    send({\n+      type: \"response\",\n+      id: req.id,\n+      ok: true,\n+      result: {\n+        id: \"run-tg-1\",\n+        requestId: \"req-tg-1\",\n+        status: \"finished\",\n+        result: JSON.stringify({ title: \"Out of process\" }),\n+        model: { id: \"default\" },\n+        durationMs: 3,\n+      },\n+    });\n+    return;\n+  }\n+  if (req.type === \"closeSession\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"close\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    rawWrite(\"\", () => process.exit(0));\n+  }\n+});\n+rl.on(\"close\", () => process.exit(0));\n+`;\n+\n+const openInput = {\n+  operation: \"create\" as const,\n+  options: { model: { id: \"default\" } },\n+  threadId: ThreadId.make(\"thread-worker-test\"),\n+  providerSessionId: ProviderSessionId.make(\"provider-session-worker-test\"),\n+};\n+\n+describe(\"CursorAgentSdkWorkerProtocol\", () => {\n+  it(\"preserves SDK error classification, rate limits, and abort causes without loading @cursor/sdk\", () => {\n+    const configErr = tagCursorSdkError(\n+      new Error(\"Cannot use this model: mystery\"),\n+      \"ConfigurationError\",\n+    );\n+    const restoredConfig = deserializeWorkerError(serializeWorkerError(configErr));\n+    assert.isTrue(isCursorSdkError(restoredConfig, \"ConfigurationError\"));\n+    assert.isTrue(isCursorSdkError(restoredConfig, \"CursorSdkError\"));\n+    assert.isFalse(isCursorSdkError(restoredConfig, \"AuthenticationError\"));\n+\n+    const rateErr = Object.assign(new Error(\"Quota exceeded\"), {\n+      name: \"RateLimitError\",\n+      code: \"PRO_USER_USAGE_LIMIT\",\n+      status: 429,\n+    });\n+    const restoredResult = deserializeRunResult(\n+      serializeRunResult({\n+        id: \"r1\",\n+        requestId: \"req1\",\n+        status: \"error\",\n+        model: { id: \"default\" },\n+        durationMs: 1,\n+        error: rateErr,\n+      } as never),\n+    );\n+    assert.isTrue(CursorAgentSdk.isCursorUsageLimitError(restoredResult.error));\n+    assert.equal(restoredResult.error?.message, \"Quota exceeded\");\n+\n+    const abortInner = Object.assign(new Error(\"aborted\"), { name: \"AbortError\" });\n+    const wrappedAbort = new Error(\"outer\", { cause: abortInner });\n+    const restoredAbort = deserializeWorkerError(serializeWorkerError(wrappedAbort));\n+    assert.isTrue(CursorAgentSdk.isCursorCancellationError(restoredAbort));\n+\n+    const nullProto = Object.create(null) as Record<string, unknown>;\n+    const restoredNullProto = deserializeWorkerError(serializeWorkerError(nullProto));\n+    assert.equal(restoredNullProto.message, \"[Unserializable error]\");\n+  });\n+});\n+\n+describe(\"CursorAgentSdkProcessRunner\", () => {\n+  const writeFakeWorker = Effect.gen(function* () {\n+    const fs = yield* FileSystem.FileSystem;\n+    const path = yield* Path.Path;\n+    const dir = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-cursor-worker-test-\" });\n+    const scriptPath = path.join(dir, \"fake-worker.cjs\");\n+    yield* fs.writeFileString(scriptPath, FAKE_WORKER_SCRIPT);\n+    return scriptPath;\n+  });\n+\n+  it.live(\n+    \"runs a full session out of process with ordered deltas, scope hooks, and clean shutdown\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const registeredPids: Array<number> = [];\n+          const unregisteredPids: Array<number> = [];\n+          const stoppedUnits: Array<string> = [];\n+          const protocolEvents: Array<string> = [];\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              registerProcess: (pid) => {\n+                registeredPids.push(pid);\n+                return () => unregisteredPids.push(pid);\n+              },\n+            }),\n+            protocolLoggerFor: () => (event) =>\n+              Effect.sync(() => {\n+                protocolEvents.push(event.payload.type);\n+              }),\n+          }).pipe(\n+            Effect.provideService(AgentScope, {\n+              wrap: ({ command, args, name }) =>\n+                Effect.succeed({ command, args, unit: `unit-${name}` }),\n+              oomKilled: () => Effect.succeed(false),\n+              stop: (unit) =>\n+                Effect.sync(() => {\n+                  stoppedUnits.push(unit);\n+                }),\n+              kill: () => Effect.succeed(false),\n+              clear: () => Effect.void,\n+            }),\n+          );\n+\n+          const session = yield* runner.open(openInput);\n+          assert.equal(session.agentId, \"agent-worker-1\");\n+          assert.isTrue(session.isAlive?.());\n+          const otherSession = yield* runner.open({\n+            ...openInput,\n+            threadId: ThreadId.make(\"thread-worker-test-2\"),\n+            providerSessionId: ProviderSessionId.make(\"provider-session-worker-test-2\"),\n+          });\n+          yield* otherSession.close;\n+          assert.isFalse(otherSession.isAlive?.());\n+          assert.isTrue(session.isAlive?.());\n+          assert.lengthOf(registeredPids, 1);\n+          assert.deepEqual(unregisteredPids, []);\n+\n+          const receivedDeltas: Array<string> = [];\n+          const firstDeltaGate = yield* Deferred.make<void>();\n+          const run = yield* session.send({\n+            message: \"hi\",\n+            onDelta: (update) =>\n+              Effect.gen(function* () {\n+                const text = (update as { readonly text?: string }).text ?? \"\";\n+                if (text === \"early-\") {\n+                  yield* Deferred.succeed(firstDeltaGate, undefined);\n+                }\n+                receivedDeltas.push(text);\n+              }),\n+          });\n+          assert.equal(run.runId, \"run-worker-1\");\n+          yield* Deferred.await(firstDeltaGate);\n+\n+          const steerOutcome = yield* run.steer!(\"change course\");\n+          assert.equal(steerOutcome, \"complete_delivered\");\n+\n+          const result = yield* run.wait;\n+          assert.equal(result.status, \"finished\");\n+          assert.equal(result.result, \"early-late\");\n+          assert.deepEqual(receivedDeltas, [\"early-\", \"late\"]);\n+\n+          const [messagesA, messagesB] = yield* Effect.all(\n+            [session.listMessages, session.listMessages],\n+            { concurrency: \"unbounded\" },\n+          );\n+          assert.lengthOf(messagesA, 1);\n+          assert.lengthOf(messagesB, 1);\n+          const usage = yield* session.readContextUsage!;\n+          assert.deepEqual(usage, { usedTokens: 120, maxTokens: 1000 });\n+          assert.isTrue(yield* session.runCheckpointed!(\"run-worker-1\"));\n+          assert.isFalse(yield* session.runCheckpointed!(\"other\"));\n+          yield* session.rewindAfterRun!(\"run-worker-1\");\n+          yield* session.close;\n+          assert.isFalse(session.isAlive?.());\n+\n+          assert.deepEqual(unregisteredPids, registeredPids);\n+          assert.deepEqual(stoppedUnits, [\"unit-cursor-sdk\"]);\n+          assert.include(protocolEvents, \"agent.open\");\n+          assert.include(protocolEvents, \"agent.opened\");\n+          assert.include(protocolEvents, \"run.started\");\n+          assert.include(protocolEvents, \"interaction.update\");\n+          assert.include(protocolEvents, \"run.completed\");\n+          assert.include(protocolEvents, \"agent.close\");\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"preserves ConfigurationError classification across IPC and cleans up on open failure\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          let unregistered = false;\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"config-error\" },\n+              registerProcess: () => () => {\n+                unregistered = true;\n+              },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const error = yield* Effect.flip(runner.open(openInput));\n+          assert.isTrue(isCursorSdkError(error.cause, \"ConfigurationError\"));\n+          assert.isTrue(\n+            error.cause instanceof Error &&\n+              error.cause.message.startsWith(\"Cannot use this model:\"),\n+          );\n+          assert.isTrue(unregistered);\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"fails run.wait with exit code and stderr when the worker crashes mid-run\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const unregistered = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"crash-mid-run\" },\n+            registerProcess: () => () => {\n+              Deferred.doneUnsafe(unregistered, Exit.void);\n+            },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+\n+        const session = yield* runner.open(openInput);\n+        const run = yield* session.send({ message: \"hi\" });\n+        const error = yield* Effect.flip(run.wait);\n+        const msg = CursorAgentSdk.cursorSdkFailureMessage(error);\n+        assert.include(msg, \"code 17\");\n+        assert.notInclude(msg, \"fatal worker boom\");\n+        const diagnostic = error.cause instanceof Error ? error.cause.cause : undefined;\n+        assert.isTrue(\n+          diagnostic instanceof Error && diagnostic.message.includes(\"fatal worker boom\"),\n+        );\n+        // Dead worker scope tears down immediately instead of waiting for sessions to close.\n+        yield* Deferred.await(unregistered);\n+        assert.isFalse(session.isAlive?.());\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"preserves an already-received runDone when the worker exits while onDelta is running\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const workerTerminated = yield* Deferred.make<void>();\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"exit-after-done\" },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+            onWorkerTerminated: () => {\n+              Deferred.doneUnsafe(workerTerminated, Exit.void);\n+            },\n+          });\n+\n+          const session = yield* runner.open(openInput);\n+          const deltaStarted = yield* Deferred.make<void>();\n+          const releaseDelta = yield* Deferred.make<void>();\n+          const run = yield* session.send({\n+            message: \"hi\",\n+            onDelta: (update) =>\n+              Effect.gen(function* () {\n+                if ((update as { readonly text?: string }).text === \"early-\") {\n+                  yield* Deferred.succeed(deltaStarted, undefined);\n+                  yield* Deferred.await(releaseDelta);\n+                }\n+              }),\n+          });\n+          yield* Deferred.await(deltaStarted);\n+          yield* Deferred.await(workerTerminated);\n+          yield* Deferred.succeed(releaseDelta, undefined);\n+          const result = yield* run.wait;\n+          assert.equal(result.status, \"finished\");\n+          assert.equal(result.result, \"early-late\");\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"cancels a started run when send is interrupted before handing it off\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const startedLogged = yield* Deferred.make<void>();\n+        const cancelled = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"cancel\" },\n+          }),\n+          protocolLoggerFor: () => (event) => {\n+            if (event.payload.type === \"run.started\") {\n+              return Deferred.succeed(startedLogged, undefined).pipe(Effect.andThen(Effect.never));\n+            }\n+            if (event.payload.type === \"run.cancel\" && event.direction === \"incoming\") {\n+              return Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid);\n+            }\n+            return Effect.void;\n+          },\n+        });\n+        const session = yield* runner.open(openInput);\n+        const sending = yield* Effect.forkChild(session.send({ message: \"hi\" }));\n+        yield* Deferred.await(startedLogged);\n+        yield* Fiber.interrupt(sending);\n+        yield* Deferred.await(cancelled);\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"closes the session when send is interrupted after transmission before acknowledgment\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const receivedByWorker = yield* Deferred.make<void>();\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"hang-send\" },\n+            }),\n+            protocolLoggerFor: () => (event) =>\n+              event.payload.type === \"run.started\"\n+                ? Deferred.succeed(receivedByWorker, undefined).pipe(Effect.asVoid)\n+                : Effect.void,\n+          });\n+\n+          const session = yield* runner.open(openInput);\n+          assert.isTrue(session.isAlive?.());\n+          const sending = yield* Effect.forkChild(session.send({ message: \"hi\" }));\n+          yield* Deferred.await(receivedByWorker);\n+          yield* Fiber.interrupt(sending);\n+          assert.isFalse(session.isAlive?.());\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"cancels an interrupted text generation in a worker that other sessions keep alive\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const received = yield* Deferred.make<void>();\n+        const cancelled = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"hang-text\" },\n+          }),\n+          protocolLoggerFor: () => (event) =>\n+            event.payload.type === \"run.started\"\n+              ? Deferred.succeed(received, undefined).pipe(Effect.asVoid)\n+              : event.payload.type === \"run.cancel\"\n+                ? Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid)\n+                : Effect.void,\n+        });\n+        const session = yield* runner.open(openInput);\n+        const generating = yield* Effect.forkChild(\n+          runner.textGenerate!({\n+            prompt: \"title\",\n+            apiKey: \"key\",\n+            model: { id: \"default\" },\n+            cwd: \"/tmp\",\n+            stateRoot: \"/tmp\",\n+          }),\n+        );\n+        yield* Deferred.await(received);\n+        yield* Fiber.interrupt(generating);\n+        yield* Deferred.await(cancelled);\n+        assert.isTrue(session.isAlive?.());\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"forwards cancel and runs textGenerate in a disposable child process\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+\n+        const cancelRunner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"cancel\" },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+        const session = yield* cancelRunner.open(openInput);\n+        const run = yield* session.send({ message: \"hi\" });\n+        yield* run.cancel;\n+        const cancelled = yield* run.wait;\n+        assert.equal(cancelled.status, \"cancelled\");\n+        yield* session.close;\n+\n+        let textGenUnregistered = false;\n+        const textGenRunner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"rate-limit-text\" },\n+            registerProcess: () => () => {\n+              textGenUnregistered = true;\n+            },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+        const textResult = yield* textGenRunner.textGenerate!({\n+          prompt: \"title\",\n+          apiKey: \"key\",\n+          model: { id: \"default\" },\n+          cwd: \"/tmp\",\n+          stateRoot: \"/tmp\",\n+        });\n+        assert.equal(textResult.status, \"error\");\n+        assert.isTrue(CursorAgentSdk.isCursorUsageLimitError(textResult.error));\n+        assert.isTrue(textGenUnregistered);\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"settles active runs on a closed session without disrupting peer sessions on the shared worker\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const registeredPids: Array<number> = [];\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"cancel\" },\n+              registerProcess: (pid) => {\n+                registeredPids.push(pid);\n+                return () => {};\n+              },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const sessionA = yield* runner.open(openInput);\n+          const sessionB = yield* runner.open({\n+            ...openInput,\n+            threadId: ThreadId.make(\"thread-worker-test-peer\"),\n+            providerSessionId: ProviderSessionId.make(\"provider-session-worker-test-peer\"),\n+          });\n+          assert.lengthOf(registeredPids, 1);\n+\n+          // Start a run on sessionA that stays pending, then close sessionA while sessionB keeps the worker alive.\n+          const runA = yield* sessionA.send({ message: \"hi\" });\n+          const waitA = yield* Effect.forkChild(Effect.flip(runA.wait));\n+          yield* sessionA.close;\n+          const errorA = yield* Fiber.join(waitA);\n+          assert.include(CursorAgentSdk.cursorSdkFailureMessage(errorA), \"closed\");\n+          assert.isFalse(sessionA.isAlive?.());\n+          assert.isTrue(sessionB.isAlive?.());\n+          assert.lengthOf(yield* sessionB.listMessages, 1);\n+          yield* sessionB.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"forwards background shell events across IPC, routes stop(), and ends orphans on worker crash\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"background-shell\" },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const events: Array<object> = [];\n+          const startedFirst = yield* Deferred.make<() => void>();\n+          const bothEnded = yield* Deferred.make<void>();\n+          let endedCount = 0;\n+\n+          const session = yield* runner.open(openInput);\n+          const run = yield* session.send({\n+            message: \"watch it\",\n+            onBackgroundShell: (event) =>\n+              Effect.gen(function* () {\n+                if (event.type === \"started\") {\n+                  const { stop, ...started } = event;\n+                  events.push(started);\n+                  if (event.id === \"sh-1\") yield* Deferred.succeed(startedFirst, stop);\n+                  return;\n+                }\n+                events.push(event);\n+                endedCount += 1;\n+                if (endedCount === 2) yield* Deferred.succeed(bothEnded, undefined);\n+              }),\n+          });\n+          yield* run.wait;\n+\n+          // Stopping sh-1 triggers a worker-side ended event, then the fake worker crashes to\n+          // verify sh-2 gets a synthesized ended(stopped: true) event.\n+          const stopFirst = yield* Deferred.await(startedFirst);\n+          stopFirst();\n+          yield* Deferred.await(bothEnded);\n+\n+          assert.deepEqual(events, [\n+            { type: \"started\", id: \"sh-1\", pid: 4101, command: \"sleep 60\" },\n+            { type: \"started\", id: \"sh-2\", pid: 4102, command: \"tail -f\" },\n+            {\n+              type: \"ended\",\n+              id: \"sh-1\",\n+              pid: 4101,\n+              command: \"sleep 60\",\n+              stopped: true,\n+              exitCode: undefined,\n+              outputPath: undefined,\n+            },\n+            {\n+              type: \"ended\",\n+              id: \"sh-2\",\n+              pid: 4102,\n+              command: \"tail -f\",\n+              stopped: true,\n+              exitCode: undefined,\n+              outputPath: undefined,\n+            },\n+          ]);\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+});\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts\nnew file mode 100644\nindex 0000000000..ed97c62288\n--- /dev/null\n+++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts\n@@ -0,0 +1,1167 @@\n+import type { AgentMessage, InteractionUpdate, RunResult, SteerAckOutcome } from \"@cursor/sdk\";\n+import * as ProviderEventLoggers from \"@t3tools/provider-core/server/ProviderEventLoggers\";\n+import { AgentScope } from \"@t3tools/shared/AgentScope\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n+import * as Cause from \"effect/Cause\";\n+import * as Deferred from \"effect/Deferred\";\n+import * as Duration from \"effect/Duration\";\n+import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n+import * as Fiber from \"effect/Fiber\";\n+import * as Layer from \"effect/Layer\";\n+import * as Option from \"effect/Option\";\n+import * as ChildProcess from \"effect/process/ChildProcess\";\n+import * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\n+import * as Queue from \"effect/Queue\";\n+import * as Ref from \"effect/Ref\";\n+import * as Scope from \"effect/Scope\";\n+import * as Semaphore from \"effect/Semaphore\";\n+import * as Stream from \"effect/Stream\";\n+\n+import * as CursorAgentSdk from \"./CursorAgentSdk.ts\";\n+import {\n+  type CursorWorkerMessage,\n+  type CursorWorkerRequest,\n+  type CursorWorkerResponsePayload,\n+  type SerializedRunResult,\n+  type SerializedRunnerFailure,\n+  decodeWorkerFrame,\n+  deserializeRunResult,\n+  deserializeWorkerError,\n+  encodeWorkerFrame,\n+} from \"./CursorAgentSdkWorkerProtocol.ts\";\n+\n+const WORKER_CLOSE_TIMEOUT = Duration.seconds(3);\n+const WORKER_EXIT_TIMEOUT = Duration.seconds(2);\n+const MAX_STDERR_CHARS = 8_192;\n+\n+export interface CursorSdkWorkerLaunch {\n+  readonly command: string;\n+  readonly args: ReadonlyArray<string>;\n+  readonly env?: NodeJS.ProcessEnv | undefined;\n+  readonly registerProcess?: ((pid: number) => () => void) | undefined;\n+}\n+\n+type RunQueueItem =\n+  | { readonly _tag: \"delta\"; readonly update: InteractionUpdate }\n+  | { readonly _tag: \"done\"; readonly ok: true; readonly result: RunResult }\n+  | {\n+      readonly _tag: \"done\";\n+      readonly ok: false;\n+      readonly error: CursorAgentSdk.CursorAgentSdkRunnerError;\n+    };\n+\n+interface ActiveWorkerRun {\n+  readonly sessionId: number;\n+  readonly queue: Queue.Queue<RunQueueItem>;\n+  readonly waitDeferred: Deferred.Deferred<RunResult, CursorAgentSdk.CursorAgentSdkRunnerError>;\n+  doneEnqueued: boolean;\n+}\n+\n+function toRunnerError(method: string, cause: unknown): CursorAgentSdk.CursorAgentSdkRunnerError {\n+  return CursorAgentSdk.isCursorAgentSdkRunnerError(cause)\n+    ? cause\n+    : new CursorAgentSdk.CursorAgentSdkRunnerError({ method, cause });\n+}\n+\n+function fromSerializedFailure(\n+  failure: SerializedRunnerFailure,\n+): CursorAgentSdk.CursorAgentSdkRunnerError {\n+  return new CursorAgentSdk.CursorAgentSdkRunnerError({\n+    method: failure.method,\n+    cause: deserializeWorkerError(failure.cause),\n+  });\n+}\n+\n+function workerExitError(method: string, exitCode: number | undefined, stderr: string) {\n+  const trimmedStderr = stderr.trim();\n+  const detail = `Cursor SDK worker exited unexpectedly${exitCode === undefined ? \"\" : ` (code ${exi",
      "stagedSummary": " apps/server/package.json                           |    2 +-\n apps/server/src/binMain.ts                         |    6 +\n ...viderOrchestrationAdapterInfrastructure.test.ts |   37 +\n .../ProviderOrchestrationAdapterInfrastructure.ts  |   36 +-\n packages/provider-cursor/package.json              |   10 +-\n .../src/server/CursorAgentSdk.test.ts              |  104 +-\n .../provider-cursor/src/server/CursorAgentSdk.ts   |  235 +++-\n .../src/server/CursorAgentSdkProcessRunner.test.ts |  742 +++++++++++++\n .../src/server/CursorAgentSdkProcessRunner.ts      | 1167 ++++++++++++++++++++\n .../src/server/CursorAgentSdkWorker.ts             |  647 +++++++++++\n .../src/server/CursorAgentSdkWorkerProtocol.ts     |  304 +++++\n .../provider-cursor/src/server/adapter.test.ts     |  137 +++\n packages/provider-cursor/src/server/adapter.ts     |    3 +-\n packages/provider-cursor/src/server/driver.ts      |    1 +\n packages/provider-cursor/src/server/sdk.ts         |   42 +-\n .../src/server/textGeneration.test.ts              |   37 +\n .../provider-cursor/src/server/textGeneration.ts   |  279 +++--\n ...r__sdk@1.4.1.patch => @cursor__sdk@1.4.2.patch} |  101 +-\n pnpm-lock.yaml                                     |   58 +-\n pnpm-workspace.yaml                                |    4 +-\n 20 files changed, 3727 insertions(+), 225 deletions(-)\n"
    }
  },
  {
    "side": "after",
    "results": [
      {
        "side": "after",
        "run": 1,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-5eed6c87-2724-4c68-8e3a-69480af673fb",
              "requestId": "7ead0231-7291-4f6f-b01a-88a365b6fc52",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add process runner, NDJSON worker protocol, and __cursor-sdk-worker CLI\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 5157,
              "usage": {
                "inputTokens": 15008,
                "outputTokens": 357,
                "cacheReadTokens": 0,
                "cacheWriteTokens": 0,
                "totalTokens": 15365,
                "reasoningTokens": 276
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes, and return a JSON object with keys: subject and body.\n\nAnalyzing the staged files and patch to identify the primary change.\n\nThe primary change is isolating the Cursor Agent SDK into an out-of-process worker via a process runner. This includes a new `CursorAgentSdkWorker`, a server CLI fast path, switching provider orchestration to use ProcessRunner, shared SqliteLocalAgentStore per workspace, and upgrading @cursor/sdk from 1.4.1 to 1.4.2.\n\nDrafting the commit message now. The subject will be \"Run Cursor Agent SDK in an out-of-process worker\". The body will list the process runner, NDJSON protocol, CLI fast path, shared SQLite store, and SDK bump.",
                        "thinkingDurationMs": 3090
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add process runner, NDJSON worker protocol, and __cursor-sdk-worker CLI\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add process runner, NDJSON worker protocol, and __cursor-sdk-worker CLI\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 8816
      },
      {
        "side": "after",
        "run": 2,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-601313ee-362a-4ae5-8e29-425a02f5dbb0",
              "requestId": "9c128a3c-c0b2-44a6-ae50-bb0366b7752e",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI entry\\n- Wire orchestration to spawn the worker; bump @cursor/sdk to 1.4.2\\n- Ref-count shared SqliteLocalAgentStore per workspace with noop runEvents\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 4892,
              "usage": {
                "inputTokens": 15008,
                "outputTokens": 323,
                "cacheReadTokens": 896,
                "cacheWriteTokens": 0,
                "totalTokens": 15331,
                "reasoningTokens": 236
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes.\n\nThe commit message must be a JSON object with keys subject and body.\n\nThe staged changes cover an SDK upgrade, a new out-of-process Cursor SDK worker with CLI fast path, wiring the orchestration adapter to use ProcessRunner, shared SqliteLocalAgentStore per workspace, text generation updates, and extensive tests.\n\nThe subject is \"Run Cursor Agent SDK in an out-of-process worker\". The body will list the key changes.",
                        "thinkingDurationMs": 2030
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI entry\\n- Wire orchestration to spawn the worker; bump @cursor/sdk to 1.4.2\\n- Ref-count shared SqliteLocalAgentStore per workspace with noop runEvents\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI entry\n- Wire orchestration to spawn the worker; bump @cursor/sdk to 1.4.2\n- Ref-count shared SqliteLocalAgentStore per workspace with noop runEvents"
            }
          }
        ],
        "success": true,
        "elapsedMs": 8403
      },
      {
        "side": "after",
        "run": 3,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-2141f9aa-5fa9-4333-a761-fa4a6311c8b9",
              "requestId": "e7469af1-e6a5-4b7c-b676-3dfade25f233",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, process runner, and protocol\\n- Ref-count shared SqliteLocalAgentStore per workspace; noop runEvents append\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 4920,
              "usage": {
                "inputTokens": 15008,
                "outputTokens": 287,
                "cacheReadTokens": 896,
                "cacheWriteTokens": 0,
                "totalTokens": 15295,
                "reasoningTokens": 211
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes they've provided.\n\nReviewing the diff to identify the primary change.\n\nThe primary change is isolating the Cursor Agent SDK into an out-of-process worker. The subject line will be \"Run Cursor Agent SDK in an out-of-process worker\".\n\nThe body will list secondary changes. The process runner and worker architecture is the main theme.",
                        "thinkingDurationMs": 2655
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, process runner, and protocol\\n- Ref-count shared SqliteLocalAgentStore per workspace; noop runEvents append\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker CLI, process runner, and protocol\n- Ref-count shared SqliteLocalAgentStore per workspace; noop runEvents append\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 6568
      },
      {
        "side": "after",
        "run": 4,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-f7860d45-1492-4532-8edc-64007326460c",
              "requestId": "a865cc14-4af4-45c3-ae2b-22fa28bb9227",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK out of process via worker\",\n  \"body\": \"- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI path\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 5484,
              "usage": {
                "inputTokens": 15008,
                "outputTokens": 339,
                "cacheReadTokens": 896,
                "cacheWriteTokens": 0,
                "totalTokens": 15347,
                "reasoningTokens": 261
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes, and return a JSON object with keys: subject and body.\n\nThe changes include an upgrade to @cursor/sdk.\n\nThe SDK upgrades from 1.1 to 1.4.2. A new out-of-process Cursor SDK worker runs via a dedicated process runner. The CLI gains a `__cursor-sdk-worker` fast path. Provider orchestration now uses the external worker instead of in-process execution. Workspace SQLite stores are shared and ref-counted with noop run events. Text generation and tests were updated.",
                        "thinkingDurationMs": 3404
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK out of process via worker\",\n  \"body\": \"- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI path\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK out of process via worker",
              "body": "- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI path\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 9202
      },
      {
        "side": "after",
        "run": 5,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-fde1e2e4-a6a2-4e89-8d20-a26403a5543e",
              "requestId": "785c3116-e02b-46af-a974-fd50631bfce9",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 4590,
              "usage": {
                "inputTokens": 15011,
                "outputTokens": 289,
                "cacheReadTokens": 896,
                "cacheWriteTokens": 0,
                "totalTokens": 15300,
                "reasoningTokens": 216
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes.\n\nThe primary change is running the Cursor Agent SDK out-of-process via a dedicated worker process. This includes a new worker implementation, CLI fast path, and provider orchestration switch to ProcessRunner. It also adds textGenerate support, shared SqliteLocalAgentStore, and an @cursor/sdk upgrade.",
                        "thinkingDurationMs": 2547
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker CLI, protocol, and process runner\n- Share ref-counted workspace SQLite stores with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 9476
      },
      {
        "side": "after",
        "run": 6,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "event": "run.result",
            "result": {
              "id": "run-5d69d731-8a27-4b22-8619-390ece9dbc9f",
              "requestId": "92501f25-e67c-43d2-a472-ab1f3ec5d903",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, process runner, and protocol\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 5114,
              "usage": {
                "inputTokens": 15005,
                "outputTokens": 287,
                "cacheReadTokens": 896,
                "cacheWriteTokens": 0,
                "totalTokens": 15292,
                "reasoningTokens": 214
              }
            }
          },
          {
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes.\n\nThe commit message must be a JSON object with subject and body keys.\n\nThe primary change isolates the Cursor Agent SDK in a dedicated out-of-process worker. It adds a process runner, worker implementation, and protocol. It also bumps `@cursor/sdk` to 1.4.2 and adds workspace SQLite ref-counting.",
                        "thinkingDurationMs": 2602
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, process runner, and protocol\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker CLI, process runner, and protocol\n- Share ref-counted workspace SQLite stores with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 6320
      }
    ],
    "input": {
      "stagedPatch": "diff --git a/apps/server/package.json b/apps/server/package.json\nindex e9f211891a..8ece0aaa81 100644\n--- a/apps/server/package.json\n+++ b/apps/server/package.json\n@@ -37,7 +37,7 @@\n   },\n   \"dependencies\": {\n     \"@anthropic-ai/claude-agent-sdk\": \"^0.3.321\",\n-    \"@cursor/sdk\": \"1.4.1\",\n+    \"@cursor/sdk\": \"1.4.2\",\n     \"@effect/platform-node\": \"catalog:\",\n     \"@effect/platform-node-shared\": \"catalog:\",\n     \"@ff-labs/fff-node\": \"0.11.0\",\ndiff --git a/apps/server/src/binMain.ts b/apps/server/src/binMain.ts\nindex 0dabd73873..7d4c93fb04 100644\n--- a/apps/server/src/binMain.ts\n+++ b/apps/server/src/binMain.ts\n@@ -30,6 +30,12 @@ export async function runCliCommand() {\n     if (mode !== \"discover\" && mode !== \"model\") throw new Error(\"Unknown speech worker mode.\");\n     const { runNativeSpeechWorker } = await import(\"./speech/native.ts\");\n     await runNativeSpeechWorker(mode, process.argv[4]);\n+  } else if (command === \"__cursor-sdk-worker\") {\n+    const [NodeServices, { runCursorSdkWorker }] = await Promise.all([\n+      import(\"@effect/platform-node/NodeServices\"),\n+      import(\"@t3tools/provider-cursor/server/worker\"),\n+    ]);\n+    await runCursorSdkWorker(NodeServices.layer);\n   } else {\n     enableCliCompileCache();\n     // Windows desktop launches without stdin; attach before reading, except on fast paths using pipes.\ndiff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\nindex 8458b46b30..981f6847ef 100644\n--- a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\n+++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\n@@ -1,8 +1,14 @@\n+import * as NodeServices from \"@effect/platform-node/NodeServices\";\n import { assert, it } from \"@effect/vitest\";\n import { ProviderDriverKind } from \"@t3tools/contracts\";\n import * as IdAllocator from \"@t3tools/provider-core/server/IdAllocator\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n import * as Effect from \"effect/Effect\";\n import * as Layer from \"effect/Layer\";\n+import * as Path from \"effect/Path\";\n+import * as ChildProcess from \"effect/process/ChildProcess\";\n+import * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\n+import * as Stream from \"effect/Stream\";\n import * as SqlClient from \"effect/sql/SqlClient\";\n \n import * as SqlitePersistence from \"../persistence/Sqlite.ts\";\n@@ -40,3 +46,34 @@ it.effect(\"subagent threads stored under a legacy id keep it when re-derived\", (\n     );\n   }),\n );\n+\n+it.live(\"spawns the __cursor-sdk-worker CLI fast path and shuts down cleanly on close\", () =>\n+  Effect.scoped(\n+    Effect.gen(function* () {\n+      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n+      const path = yield* Path.Path;\n+      const executable = yield* HostProcess.ExecutablePath;\n+      const entry = yield* path.fromFileUrl(new URL(\"../bin.ts\", import.meta.url));\n+      const handle = yield* spawner.spawn(\n+        ChildProcess.make(executable, [entry, \"__cursor-sdk-worker\"], {\n+          stdin: { stream: \"pipe\", endOnDone: false },\n+          stdout: \"pipe\",\n+          stderr: \"pipe\",\n+        }),\n+      );\n+      yield* Stream.run(\n+        Stream.encodeText(Stream.make(`${JSON.stringify({ id: 1, type: \"close\" })}\\n`)),\n+        handle.stdin,\n+      );\n+      const stdout = yield* handle.stdout.pipe(Stream.decodeText(), Stream.mkString);\n+      const exitCode = Number(yield* handle.exitCode);\n+      assert.strictEqual(exitCode, 0);\n+      assert.deepStrictEqual(JSON.parse(stdout.trim()), {\n+        type: \"response\",\n+        id: 1,\n+        ok: true,\n+        result: null,\n+      });\n+    }),\n+  ).pipe(Effect.provide(NodeServices.layer)),\n+);\ndiff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\nindex b01735a7c2..ffb25e7daa 100644\n--- a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\n+++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\n@@ -1,13 +1,17 @@\n import * as Effect from \"effect/Effect\";\n import * as Layer from \"effect/Layer\";\n+import * as Path from \"effect/Path\";\n import * as SqlClient from \"effect/sql/SqlClient\";\n \n import * as ClaudeAdapterV2 from \"../orchestration-v2/Adapters/ClaudeAdapterV2.ts\";\n import * as CodexAdapterV2 from \"../orchestration-v2/Adapters/CodexAdapterV2.ts\";\n-import * as CursorAgentSdk from \"@t3tools/provider-cursor/server/CursorAgentSdk\";\n+import * as ProviderProcesses from \"../process/providerProcesses.ts\";\n+import type * as CursorAgentSdk from \"@t3tools/provider-cursor/server/CursorAgentSdk\";\n+import * as CursorAgentSdkProcessRunner from \"@t3tools/provider-cursor/server/CursorAgentSdkProcessRunner\";\n import * as CursorSdk from \"@t3tools/provider-cursor/server/CursorSdk\";\n import * as IdAllocator from \"@t3tools/provider-core/server/IdAllocator\";\n import * as ProviderContinuationRequests from \"@t3tools/provider-core/server/ProviderContinuationRequests\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n \n export type ProviderOrchestrationAdapterInfrastructure =\n   | ClaudeAdapterV2.ClaudeAgentSdkQueryRunner\n@@ -34,11 +38,39 @@ export const layerIdAllocator = Layer.unwrap(\n   }),\n );\n \n+const resolveCursorWorkerLaunch = Effect.gen(function* () {\n+  const path = yield* Path.Path;\n+  const command = yield* HostProcess.ExecutablePath;\n+  const isExecutable = yield* HostProcess.IsExecutable;\n+  const providerProcesses = yield* ProviderProcesses.ProviderProcesses;\n+  // In a bundle import.meta.url is bin.mjs; development and tests use this source module.\n+  const entry = yield* path\n+    .fromFileUrl(\n+      new URL(import.meta.url.endsWith(\".ts\") ? \"../bin.ts\" : \"./bin.mjs\", import.meta.url),\n+    )\n+    .pipe(Effect.orDie);\n+  return {\n+    command,\n+    args: [...(isExecutable ? [] : [entry]), \"__cursor-sdk-worker\"],\n+    ...(providerProcesses.register === undefined\n+      ? {}\n+      : { registerProcess: providerProcesses.register }),\n+  };\n+});\n+\n /** Reuse the continuation worker's exact layer reference so memoization shares one queue. */\n export const layer = Layer.mergeAll(\n   ClaudeAdapterV2.layerQueryRunner,\n   CodexAdapterV2.layerAppServerClientFactory,\n-  CursorAgentSdk.layer.pipe(Layer.provideMerge(CursorSdk.layer)),\n+  Layer.unwrap(\n+    Effect.gen(function* () {\n+      const path = yield* Path.Path;\n+      return CursorAgentSdkProcessRunner.layer(\n+        resolveCursorWorkerLaunch.pipe(Effect.provideService(Path.Path, path)),\n+      );\n+    }),\n+  ),\n+  CursorSdk.layer,\n   layerIdAllocator,\n   ProviderContinuationRequests.layer,\n );\ndiff --git a/packages/provider-cursor/package.json b/packages/provider-cursor/package.json\nindex e1d101a92f..dcd6bd0904 100644\n--- a/packages/provider-cursor/package.json\n+++ b/packages/provider-cursor/package.json\n@@ -23,6 +23,14 @@\n       \"types\": \"./src/server/CursorAgentSdk.ts\",\n       \"import\": \"./src/server/CursorAgentSdk.ts\"\n     },\n+    \"./server/CursorAgentSdkProcessRunner\": {\n+      \"types\": \"./src/server/CursorAgentSdkProcessRunner.ts\",\n+      \"import\": \"./src/server/CursorAgentSdkProcessRunner.ts\"\n+    },\n+    \"./server/worker\": {\n+      \"types\": \"./src/server/CursorAgentSdkWorker.ts\",\n+      \"import\": \"./src/server/CursorAgentSdkWorker.ts\"\n+    },\n     \"./server/accountUsage\": {\n       \"types\": \"./src/server/accountUsage.ts\",\n       \"import\": \"./src/server/accountUsage.ts\"\n@@ -45,7 +53,7 @@\n     \"test\": \"vp test run --config ../../vite.config.ts --dir .\"\n   },\n   \"dependencies\": {\n-    \"@cursor/sdk\": \"1.4.1\",\n+    \"@cursor/sdk\": \"1.4.2\",\n     \"@t3tools/contracts\": \"workspace:*\",\n     \"@t3tools/provider-core\": \"workspace:*\",\n     \"@t3tools/shared\": \"workspace:*\",\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\nindex 187ce35990..94ae520513 100644\n--- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\n+++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\n@@ -60,7 +60,7 @@ const cursorSdkMock = vi.hoisted(() => {\n       };\n     },\n   );\n-  const create = vi.fn(async () => ({\n+  const create = vi.fn(async (_options?: unknown) => ({\n     agentId: \"agent-cursor-agent-sdk-test\",\n     send,\n     close: agentClose,\n@@ -87,6 +87,8 @@ const cursorSdkMock = vi.hoisted(() => {\n     );\n   });\n \n+  const sqliteOpen = vi.fn<() => Promise<unknown>>(async () => undefined);\n+\n   return {\n     agentClose,\n     cancelRun,\n@@ -99,6 +101,7 @@ const cursorSdkMock = vi.hoisted(() => {\n     runSteer,\n     runWait,\n     send,\n+    sqliteOpen,\n     setAgentCloseFailure: (failure: unknown) => {\n       agentCloseFailure = failure;\n     },\n@@ -121,7 +124,7 @@ vi.mock(\"./sdk.ts\", () => ({\n     },\n     createAgentPlatform: vi.fn(),\n   }),\n-  loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: vi.fn() } }),\n+  loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: cursorSdkMock.sqliteOpen } }),\n }));\n \n const layerTest = CursorAgentSdk.layer.pipe(\n@@ -509,4 +512,101 @@ describe(\"CursorAgentSdkRunner\", () => {\n       assert.equal(yield* plain.steer!(\"later\"), \"revert_to_followup\");\n     }).pipe(Effect.provide(layerTest)),\n   );\n+\n+  it.effect(\n+    \"ref-counts one disposable SqliteLocalAgentStore with no-op runEvents per workspace\",\n+    () =>\n+      Effect.gen(function* () {\n+        const dispose = vi.fn(async () => {});\n+        const underlyingAppend = vi.fn(async () => {\n+          throw new Error(\"runEvents.append must not hit SQLite\");\n+        });\n+        const fakeStore = {\n+          agents: { get: vi.fn() },\n+          runs: { list: vi.fn() },\n+          checkpoints: { save: vi.fn() },\n+          runEvents: { append: underlyingAppend, list: vi.fn(), delete: vi.fn() },\n+          dispose,\n+        };\n+        cursorSdkMock.sqliteOpen.mockClear();\n+        cursorSdkMock.sqliteOpen.mockResolvedValueOnce(fakeStore);\n+        cursorSdkMock.create.mockClear();\n+\n+        const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;\n+        const session = yield* runner.open({\n+          operation: \"create\",\n+          options: { local: { cwd: \"/workspace/cursor-store-test\" } },\n+          threadId: ThreadId.make(\"thread-cursor-agent-sdk-store\"),\n+          providerSessionId: ProviderSessionId.make(\"provider-session-cursor-agent-sdk-store\"),\n+        });\n+        const peer = yield* runner.open({\n+          operation: \"create\",\n+          options: { local: { cwd: \"/workspace/cursor-store-test\" } },\n+          threadId: ThreadId.make(\"thread-cursor-agent-sdk-store-peer\"),\n+          providerSessionId: ProviderSessionId.make(\"provider-session-cursor-agent-sdk-store-peer\"),\n+        });\n+\n+        assert.deepStrictEqual(cursorSdkMock.sqliteOpen.mock.calls, [\n+          [{ workspaceRef: \"/workspace/cursor-store-test\" }],\n+        ]);\n+        const passedOptions = cursorSdkMock.create.mock.calls[0]?.[0] as\n+          | {\n+              readonly local?: {\n+                readonly store?: {\n+                  readonly agents: unknown;\n+                  readonly checkpoints: unknown;\n+                  readonly runEvents: {\n+                    readonly append: (event: {\n+                      readonly runId: string;\n+                      readonly eventType: string;\n+                      readonly payload?: unknown;\n+                    }) => Promise<{ readonly seq: number }>;\n+                  };\n+                };\n+              };\n+            }\n+          | undefined;\n+        const peerOptions = cursorSdkMock.create.mock.calls[1]?.[0] as typeof passedOptions;\n+        const passedStore = passedOptions?.local?.store;\n+        assert.isDefined(passedStore);\n+        assert.strictEqual(peerOptions?.local?.store, passedStore);\n+        assert.strictEqual(passedStore?.agents, fakeStore.agents);\n+        assert.strictEqual(passedStore?.checkpoints, fakeStore.checkpoints);\n+        const appended = yield* Effect.promise(() =>\n+          passedStore!.runEvents.append({\n+            runId: \"run-1\",\n+            eventType: \"text-delta\",\n+            payload: { text: \"hi\" },\n+          }),\n+        );\n+        assert.equal(appended.seq, 1);\n+        assert.equal(underlyingAppend.mock.calls.length, 0);\n+        assert.equal(dispose.mock.calls.length, 0);\n+\n+        // Closing one session keeps the shared workspace store alive; repeated close does not double-release.\n+        yield* session.close;\n+        yield* session.close;\n+        assert.equal(dispose.mock.calls.length, 0);\n+\n+        yield* peer.close;\n+        assert.equal(dispose.mock.calls.length, 1);\n+\n+        // Failed open disposes the newly opened store instead of leaking SQLite FDs.\n+        const failingDispose = vi.fn(async () => {});\n+        cursorSdkMock.sqliteOpen.mockResolvedValueOnce({ ...fakeStore, dispose: failingDispose });\n+        cursorSdkMock.create.mockRejectedValueOnce(new Error(\"boom\"));\n+        const failed = yield* runner\n+          .open({\n+            operation: \"create\",\n+            options: { local: { cwd: \"/workspace/cursor-store-fail\" } },\n+            threadId: ThreadId.make(\"thread-cursor-agent-sdk-store-fail\"),\n+            providerSessionId: ProviderSessionId.make(\n+              \"provider-session-cursor-agent-sdk-store-fail\",\n+            ),\n+          })\n+          .pipe(Effect.exit);\n+        assert(Exit.isFailure(failed));\n+        assert.equal(failingDispose.mock.calls.length, 1);\n+      }).pipe(Effect.provide(layerTest)),\n+  );\n });\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts\nindex 75b0232ebf..81b8208a5d 100644\n--- a/packages/provider-cursor/src/server/CursorAgentSdk.ts\n+++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts\n@@ -18,10 +18,12 @@ import {\n import * as Context from \"effect/Context\";\n import * as Deferred from \"effect/Deferred\";\n import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n import * as Layer from \"effect/Layer\";\n import * as Option from \"effect/Option\";\n import * as Ref from \"effect/Ref\";\n import * as Schema from \"effect/Schema\";\n+import * as Semaphore from \"effect/Semaphore\";\n \n import * as CursorSdk from \"./CursorSdk.ts\";\n import * as ProviderEventLoggers from \"@t3tools/provider-core/server/ProviderEventLoggers\";\n@@ -165,9 +167,19 @@ export interface CursorAgentSdkSession {\n    * The open agent keeps its old conversation in memory, so reopen it before the next send.\n    */\n   readonly rewindAfterRun?: (runId: string) => Effect.Effect<void, CursorAgentSdkRunnerError>;\n+  /** False once an out-of-process worker has terminated or started closing; absent on in-process sessions. */\n+  readonly isAlive?: () => boolean;\n   readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;\n }\n \n+export interface CursorAgentSdkTextGenerateInput {\n+  readonly prompt: string;\n+  readonly apiKey: string;\n+  readonly model: NonNullable<AgentOptions[\"model\"]>;\n+  readonly cwd: string;\n+  readonly stateRoot: string;\n+}\n+\n export class CursorAgentSdkRunner extends Context.Service<\n   CursorAgentSdkRunner,\n   {\n@@ -175,6 +187,10 @@ export class CursorAgentSdkRunner extends Context.Service<\n       input: CursorAgentSdkOpenInput,\n     ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;\n     readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;\n+    /** Absent on in-process test doubles; the out-of-process runner provides it. */\n+    readonly textGenerate?: (\n+      input: CursorAgentSdkTextGenerateInput,\n+    ) => Effect.Effect<RunResult, CursorAgentSdkRunnerError>;\n   }\n >()(\"@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner\") {}\n \n@@ -414,7 +430,7 @@ export function loggedCursorSendOptions(\n   };\n }\n \n-function makeCursorAgentSdkProtocolLogger(input: {\n+export function makeCursorAgentSdkProtocolLogger(input: {\n   readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;\n   readonly threadId: ThreadId;\n   readonly providerSessionId: OrchestrationV2ProviderSession[\"id\"];\n@@ -463,6 +479,60 @@ function subscribeShellStreamOutput(listener: (output: CursorShellStreamOutput)\n   };\n }\n \n+type CursorLocalStore = NonNullable<NonNullable<AgentOptions[\"local\"]>[\"store\"]>;\n+\n+interface DisposableCursorLocalStore extends CursorLocalStore {\n+  readonly dispose: () => Promise<void>;\n+}\n+\n+function isDisposableCursorLocalStore(value: unknown): value is DisposableCursorLocalStore {\n+  return (\n+    typeof value === \"object\" &&\n+    value !== null &&\n+    \"agents\" in value &&\n+    \"runs\" in value &&\n+    \"checkpoints\" in value &&\n+    \"runEvents\" in value &&\n+    \"dispose\" in value &&\n+    typeof value.dispose === \"function\"\n+  );\n+}\n+\n+// T3 persists its own event log and never tails SDK run_events; skipping per-delta SQLite\n+// run_events writes avoids synchronous BEGIN IMMEDIATE write locks and multi-GB index.db bloat.\n+export function withNoopCursorRunEvents(store: CursorLocalStore): CursorLocalStore {\n+  if (\n+    typeof store !== \"object\" ||\n+    store === null ||\n+    typeof store.runEvents?.append !== \"function\"\n+  ) {\n+    return store;\n+  }\n+  let seq = 0;\n+  return {\n+    agents: store.agents,\n+    runs: store.runs,\n+    checkpoints: store.checkpoints,\n+    runEvents: {\n+      append: async (event) => {\n+        seq += 1;\n+        return {\n+          runId: event.runId,\n+          seq,\n+          offset: String(seq),\n+          eventType: event.eventType,\n+          payload: event.payload ?? null,\n+          payloadRef: event.payloadRef ?? null,\n+          idempotencyKey: event.idempotencyKey ?? null,\n+          createdAt: 0,\n+        };\n+      },\n+      list: async () => ({ items: [] }),\n+      delete: async () => {},\n+    },\n+  };\n+}\n+\n interface CursorBackgroundShell {\n   readonly conversationId?: unknown;\n   readonly command?: unknown;\n@@ -548,6 +618,58 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n     },\n   );\n \n+  // Ref-count one SqliteLocalAgentStore per workspace so concurrent sessions share a single\n+  // index.db handle while still disposing handles, page caches, and FDs once the last one closes.\n+  interface WorkspaceStoreLease {\n+    readonly store: DisposableCursorLocalStore;\n+    readonly wrapped: CursorLocalStore;\n+    users: number;\n+  }\n+  const workspaceStores = new Map<string, WorkspaceStoreLease>();\n+  const workspaceStoreLock = yield* Semaphore.make(1);\n+  const acquireWorkspaceStore = (workspaceRef: string, method: string) =>\n+    workspaceStoreLock.withPermits(1)(\n+      Effect.suspend(() => {\n+        const existing = workspaceStores.get(workspaceRef);\n+        if (existing !== undefined) {\n+          existing.users += 1;\n+          return Effect.succeed(existing);\n+        }\n+        return Effect.tryPromise({\n+          try: async () => {\n+            const candidate = await sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef });\n+            return isDisposableCursorLocalStore(candidate) ? candidate : undefined;\n+          },\n+          catch: (cause) => runnerError(cause, method),\n+        }).pipe(\n+          Effect.map((opened) => {\n+            if (opened === undefined) return undefined;\n+            const lease: WorkspaceStoreLease = {\n+              store: opened,\n+              wrapped: withNoopCursorRunEvents(opened),\n+              users: 1,\n+            };\n+            workspaceStores.set(workspaceRef, lease);\n+            return lease;\n+          }),\n+        );\n+      }),\n+    );\n+  const releaseWorkspaceStore = (workspaceRef: string, lease: WorkspaceStoreLease) =>\n+    workspaceStoreLock.withPermits(1)(\n+      Effect.suspend(() => {\n+        lease.users -= 1;\n+        if (lease.users > 0) return Effect.void;\n+        if (workspaceStores.get(workspaceRef) === lease) {\n+          workspaceStores.delete(workspaceRef);\n+        }\n+        return Effect.tryPromise({\n+          try: () => lease.store.dispose(),\n+          catch: () => undefined,\n+        }).pipe(Effect.ignore);\n+      }),\n+    );\n+\n   return CursorAgentSdkRunner.of({\n     open: Effect.fn(\"CursorAgentSdkRunner.open\")(function* (input) {\n       const { Agent, createAgentPlatform } = yield* Effect.try({\n@@ -573,59 +695,85 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n       });\n \n       // Cursor uses cwd for both execution and store lookup; a moved thread keeps its original store.\n-      const storeCwd = input.storeCwd;\n-      const storePlatform =\n-        input.operation === \"resume\" &&\n-        storeCwd !== undefined &&\n-        storeCwd !== input.options.local?.cwd\n-          ? yield* Effect.tryPromise({\n-              try: () =>\n-                createAgentPlatform({\n-                  workspaceRef: storeCwd,\n-                  ...(input.options.local?.store === undefined\n-                    ? {}\n-                    : { localStore: input.options.local.store }),\n-                }),\n-              catch: (cause) => runnerError(cause, \"agent.resume\"),\n-            })\n-          : undefined;\n-      const agent = yield* Effect.tryPromise({\n-        try: () =>\n-          input.operation === \"create\"\n-            ? Agent.create(input.options)\n-            : storePlatform === undefined\n-              ? Agent.resume(input.agentId!, input.options)\n-              : storePlatform.resumeAgent(input.agentId!, input.options),\n-        catch: (cause) => runnerError(cause, `agent.${input.operation}`),\n-      });\n-      let shellListener: ((event: CursorBackgroundShellEvent) => void) | undefined;\n-\n-      yield* log({\n-        direction: \"incoming\",\n-        stage: \"decoded\",\n-        payload: {\n-          type: \"agent.opened\",\n-          agentId: agent.agentId,\n-        },\n-      });\n-\n       const cwd =\n         typeof input.options.local?.cwd === \"string\"\n           ? input.options.local.cwd\n           : input.options.local?.cwd?.[0];\n+      const storeCwd = input.storeCwd;\n+      const storeWorkspace =\n+        input.operation === \"resume\" && storeCwd !== undefined ? storeCwd : cwd;\n+      const ownedStoreLease =\n+        input.options.local?.store === undefined && storeWorkspace !== undefined\n+          ? yield* acquireWorkspaceStore(storeWorkspace, `agent.${input.operation}`)\n+          : undefined;\n+      let storeReleased = false;\n+      const disposeOwnedStore =\n+        ownedStoreLease === undefined || storeWorkspace === undefined\n+          ? Effect.void\n+          : Effect.suspend(() => {\n+              if (storeReleased) return Effect.void;\n+              storeReleased = true;\n+              return releaseWorkspaceStore(storeWorkspace, ownedStoreLease);\n+            });\n+      const effectiveStore =\n+        ownedStoreLease === undefined ? input.options.local?.store : ownedStoreLease.wrapped;\n+      const effectiveOptions: AgentOptions =\n+        effectiveStore === undefined || effectiveStore === input.options.local?.store\n+          ? input.options\n+          : {\n+              ...input.options,\n+              local: {\n+                ...input.options.local,\n+                store: effectiveStore,\n+              },\n+            };\n+\n+      const { storePlatform, agent } = yield* Effect.gen(function* () {\n+        const resolvedStorePlatform =\n+          input.operation === \"resume\" &&\n+          storeCwd !== undefined &&\n+          storeCwd !== input.options.local?.cwd\n+            ? yield* Effect.tryPromise({\n+                try: () =>\n+                  createAgentPlatform({\n+                    workspaceRef: storeCwd,\n+                    ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),\n+                  }),\n+                catch: (cause) => runnerError(cause, \"agent.resume\"),\n+              })\n+            : undefined;\n+        const openedAgent = yield* Effect.tryPromise({\n+          try: () =>\n+            input.operation === \"create\"\n+              ? Agent.create(effectiveOptions)\n+              : resolvedStorePlatform === undefined\n+                ? Agent.resume(input.agentId!, effectiveOptions)\n+                : resolvedStorePlatform.resumeAgent(input.agentId!, effectiveOptions),\n+          catch: (cause) => runnerError(cause, `agent.${input.operation}`),\n+        });\n+        yield* log({\n+          direction: \"incoming\",\n+          stage: \"decoded\",\n+          payload: {\n+            type: \"agent.opened\",\n+            agentId: openedAgent.agentId,\n+          },\n+        });\n+        return { storePlatform: resolvedStorePlatform, agent: openedAgent };\n+      }).pipe(Effect.onExit((exit) => (Exit.isFailure(exit) ? disposeOwnedStore : Effect.void)));\n+      let shellListener: ((event: CursorBackgroundShellEvent) => void) | undefined;\n+\n       const runOptions = {\n         runtime: \"local\" as const,\n         ...(cwd === undefined ? {} : { cwd }),\n-        ...(input.options.local?.store === undefined ? {} : { store: input.options.local.store }),\n+        ...(effectiveStore === undefined ? {} : { store: effectiveStore }),\n       };\n       let abandonedRunRecoveryAvailable = input.operation === \"resume\";\n       const storeView = async () =>\n         storePlatform ??\n         (await createAgentPlatform({\n           ...(cwd === undefined ? {} : { workspaceRef: cwd }),\n-          ...(input.options.local?.store === undefined\n-            ? {}\n-            : { localStore: input.options.local.store }),\n+          ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),\n         }));\n \n       return {\n@@ -879,9 +1027,7 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n                   ? Agent.messages.list(agent.agentId, {\n                       runtime: \"local\",\n                       ...(cwd === undefined ? {} : { cwd }),\n-                      ...(input.options.local?.store === undefined\n-                        ? {}\n-                        : { store: input.options.local.store }),\n+                      ...(effectiveStore === undefined ? {} : { store: effectiveStore }),\n                     })\n                   : storePlatform.getAgentMessages(agent.agentId),\n               catch: (cause) => runnerError(cause, \"agent.messages.list\"),\n@@ -1010,6 +1156,7 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n               catch: (cause) => runnerError(cause, \"agent.close\"),\n             }),\n           ),\n+          Effect.ensuring(disposeOwnedStore),\n         ),\n       } satisfies CursorAgentSdkSession;\n     }),\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts\nnew file mode 100644\nindex 0000000000..430907b101\n--- /dev/null\n+++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts\n@@ -0,0 +1,742 @@\n+import * as NodeServices from \"@effect/platform-node/NodeServices\";\n+import { assert, describe, it } from \"@effect/vitest\";\n+import { ProviderSessionId, ThreadId } from \"@t3tools/contracts\";\n+import { AgentScope } from \"@t3tools/shared/AgentScope\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n+import * as Deferred from \"effect/Deferred\";\n+import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n+import * as Fiber from \"effect/Fiber\";\n+import * as FileSystem from \"effect/FileSystem\";\n+import * as Path from \"effect/Path\";\n+\n+import * as CursorAgentSdk from \"./CursorAgentSdk.ts\";\n+import * as CursorAgentSdkProcessRunner from \"./CursorAgentSdkProcessRunner.ts\";\n+import {\n+  deserializeRunResult,\n+  deserializeWorkerError,\n+  serializeRunResult,\n+  serializeWorkerError,\n+} from \"./CursorAgentSdkWorkerProtocol.ts\";\n+import { isCursorSdkError, tagCursorSdkError } from \"./sdk.ts\";\n+\n+// Minimal fake worker script implementing the NDJSON worker protocol in a real child Node process.\n+const FAKE_WORKER_SCRIPT = `\n+const readline = require(\"node:readline\");\n+const rawWrite = process.stdout.write.bind(process.stdout);\n+const send = (msg) => rawWrite(JSON.stringify(msg) + \"\\\\n\");\n+const mode = process.env.FAKE_WORKER_MODE || \"ok\";\n+\n+const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });\n+rl.on(\"line\", (line) => {\n+  if (!line.trim()) return;\n+  const req = JSON.parse(line);\n+  if (req.type === \"open\") {\n+    if (mode === \"config-error\") {\n+      send({\n+        type: \"response\",\n+        id: req.id,\n+        ok: false,\n+        error: {\n+          method: \"agent.create\",\n+          cause: {\n+            name: \"ConfigurationError\",\n+            message: \"Cannot use this model: bad-model\",\n+            sdkErrorKind: \"ConfigurationError\",\n+          },\n+        },\n+      });\n+      return;\n+    }\n+    rawWrite(\"non-json noise that must be ignored\\\\n\");\n+    send({ type: \"response\", id: req.id, ok: true, result: { agentId: \"agent-worker-1\" } });\n+    return;\n+  }\n+  if (req.type === \"send\") {\n+    if (mode === \"hang-send\") {\n+      send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.started\", runId: \"pending\", agentId: \"agent-worker-1\" } } });\n+      return;\n+    }\n+    if (mode === \"crash-mid-run\") {\n+      send({ type: \"response\", id: req.id, ok: true, result: { runId: \"run-crash\", agentId: \"agent-worker-1\" } });\n+      process.stderr.write(\"fatal worker boom\\\\n\");\n+      process.exit(17);\n+      return;\n+    }\n+    // Emit an early delta before the send response to verify parent buffering/ordering.\n+    send({ type: \"delta\", sendId: req.id, update: { type: \"text-delta\", text: \"early-\" } });\n+    send({ type: \"response\", id: req.id, ok: true, result: { runId: \"run-worker-1\", agentId: \"agent-worker-1\" } });\n+    if (mode === \"cancel\") {\n+      return;\n+    }\n+    send({ type: \"delta\", sendId: req.id, update: { type: \"text-delta\", text: \"late\" } });\n+    send({\n+      type: \"runDone\",\n+      sendId: req.id,\n+      ok: true,\n+      result: {\n+        id: \"run-worker-1\",\n+        requestId: \"req-1\",\n+        status: \"finished\",\n+        result: \"early-late\",\n+        model: { id: \"default\" },\n+        durationMs: 5,\n+      },\n+    });\n+    if (mode === \"exit-after-done\") {\n+      rawWrite(\"\", () => process.exit(0));\n+    }\n+    if (mode === \"background-shell\" && req.listenBackgroundShells) {\n+      send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"started\", id: \"sh-1\", pid: 4101, command: \"sleep 60\" } });\n+      send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"started\", id: \"sh-2\", pid: 4102, command: \"tail -f\" } });\n+    }\n+    return;\n+  }\n+  if (req.type === \"stopBackgroundShell\") {\n+    send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"ended\", id: req.shellId, pid: 4101, command: \"sleep 60\", stopped: true, exitCode: undefined, outputPath: undefined } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    if (mode === \"background-shell\") {\n+      rawWrite(\"\", () => process.exit(19));\n+    }\n+    return;\n+  }\n+  if (req.type === \"steer\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: \"complete_delivered\" });\n+    return;\n+  }\n+  if (req.type === \"cancel\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.cancel\", runId: \"run-worker-1\" } } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    send({\n+      type: \"runDone\",\n+      sendId: req.sendId,\n+      ok: true,\n+      result: {\n+        id: \"run-worker-1\",\n+        requestId: \"req-1\",\n+        status: \"cancelled\",\n+        model: { id: \"default\" },\n+        durationMs: 2,\n+      },\n+    });\n+    return;\n+  }\n+  if (req.type === \"listMessages\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: [{ id: \"m1\", role: \"assistant\", text: \"early-late\" }] });\n+    return;\n+  }\n+  if (req.type === \"readContextUsage\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: { usedTokens: 120, maxTokens: 1000 } });\n+    return;\n+  }\n+  if (req.type === \"runCheckpointed\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: req.runId === \"run-worker-1\" });\n+    return;\n+  }\n+  if (req.type === \"rewindAfterRun\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"textGenerate\" && mode === \"hang-text\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.started\", runId: \"text\", agentId: \"text\" } } });\n+    return;\n+  }\n+  if (req.type === \"cancelTextGenerate\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.cancel\", runId: \"text\" } } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"textGenerate\") {\n+    if (mode === \"rate-limit-text\") {\n+      send({\n+        type: \"response\",\n+        id: req.id,\n+        ok: true,\n+        result: {\n+          id: \"run-tg-1\",\n+          requestId: \"req-tg-1\",\n+          status: \"error\",\n+          model: { id: \"default\" },\n+          durationMs: 3,\n+          error: {\n+            name: \"RateLimitError\",\n+            message: \"Too many requests\",\n+            code: \"PRO_USER_USAGE_LIMIT\",\n+            status: 429,\n+            sdkErrorKind: \"CursorSdkError\",\n+          },\n+        },\n+      });\n+      return;\n+    }\n+    send({\n+      type: \"response\",\n+      id: req.id,\n+      ok: true,\n+      result: {\n+        id: \"run-tg-1\",\n+        requestId: \"req-tg-1\",\n+        status: \"finished\",\n+        result: JSON.stringify({ title: \"Out of process\" }),\n+        model: { id: \"default\" },\n+        durationMs: 3,\n+      },\n+    });\n+    return;\n+  }\n+  if (req.type === \"closeSession\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"close\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    rawWrite(\"\", () => process.exit(0));\n+  }\n+});\n+rl.on(\"close\", () => process.exit(0));\n+`;\n+\n+const openInput = {\n+  operation: \"create\" as const,\n+  options: { model: { id: \"default\" } },\n+  threadId: ThreadId.make(\"thread-worker-test\"),\n+  providerSessionId: ProviderSessionId.make(\"provider-session-worker-test\"),\n+};\n+\n+describe(\"CursorAgentSdkWorkerProtocol\", () => {\n+  it(\"preserves SDK error classification, rate limits, and abort causes without loading @cursor/sdk\", () => {\n+    const configErr = tagCursorSdkError(\n+      new Error(\"Cannot use this model: mystery\"),\n+      \"ConfigurationError\",\n+    );\n+    const restoredConfig = deserializeWorkerError(serializeWorkerError(configErr));\n+    assert.isTrue(isCursorSdkError(restoredConfig, \"ConfigurationError\"));\n+    assert.isTrue(isCursorSdkError(restoredConfig, \"CursorSdkError\"));\n+    assert.isFalse(isCursorSdkError(restoredConfig, \"AuthenticationError\"));\n+\n+    const rateErr = Object.assign(new Error(\"Quota exceeded\"), {\n+      name: \"RateLimitError\",\n+      code: \"PRO_USER_USAGE_LIMIT\",\n+      status: 429,\n+    });\n+    const restoredResult = deserializeRunResult(\n+      serializeRunResult({\n+        id: \"r1\",\n+        requestId: \"req1\",\n+        status: \"error\",\n+        model: { id: \"default\" },\n+        durationMs: 1,\n+        error: rateErr,\n+      } as never),\n+    );\n+    assert.isTrue(CursorAgentSdk.isCursorUsageLimitError(restoredResult.error));\n+    assert.equal(restoredResult.error?.message, \"Quota exceeded\");\n+\n+    const abortInner = Object.assign(new Error(\"aborted\"), { name: \"AbortError\" });\n+    const wrappedAbort = new Error(\"outer\", { cause: abortInner });\n+    const restoredAbort = deserializeWorkerError(serializeWorkerError(wrappedAbort));\n+    assert.isTrue(CursorAgentSdk.isCursorCancellationError(restoredAbort));\n+\n+    const nullProto = Object.create(null) as Record<string, unknown>;\n+    const restoredNullProto = deserializeWorkerError(serializeWorkerError(nullProto));\n+    assert.equal(restoredNullProto.message, \"[Unserializable error]\");\n+  });\n+});\n+\n+describe(\"CursorAgentSdkProcessRunner\", () => {\n+  const writeFakeWorker = Effect.gen(function* () {\n+    const fs = yield* FileSystem.FileSystem;\n+    const path = yield* Path.Path;\n+    const dir = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-cursor-worker-test-\" });\n+    const scriptPath = path.join(dir, \"fake-worker.cjs\");\n+    yield* fs.writeFileString(scriptPath, FAKE_WORKER_SCRIPT);\n+    return scriptPath;\n+  });\n+\n+  it.live(\n+    \"runs a full session out of process with ordered deltas, scope hooks, and clean shutdown\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const registeredPids: Array<number> = [];\n+          const unregisteredPids: Array<number> = [];\n+          const stoppedUnits: Array<string> = [];\n+          const protocolEvents: Array<string> = [];\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              registerProcess: (pid) => {\n+                registeredPids.push(pid);\n+                return () => unregisteredPids.push(pid);\n+              },\n+            }),\n+            protocolLoggerFor: () => (event) =>\n+              Effect.sync(() => {\n+                protocolEvents.push(event.payload.type);\n+              }),\n+          }).pipe(\n+            Effect.provideService(AgentScope, {\n+              wrap: ({ command, args, name }) =>\n+                Effect.succeed({ command, args, unit: `unit-${name}` }),\n+              oomKilled: () => Effect.succeed(false),\n+              stop: (unit) =>\n+                Effect.sync(() => {\n+                  stoppedUnits.push(unit);\n+                }),\n+              kill: () => Effect.succeed(false),\n+              clear: () => Effect.void,\n+            }),\n+          );\n+\n+          const session = yield* runner.open(openInput);\n+          assert.equal(session.agentId, \"agent-worker-1\");\n+          assert.isTrue(session.isAlive?.());\n+          const otherSession = yield* runner.open({\n+            ...openInput,\n+            threadId: ThreadId.make(\"thread-worker-test-2\"),\n+            providerSessionId: ProviderSessionId.make(\"provider-session-worker-test-2\"),\n+          });\n+          yield* otherSession.close;\n+          assert.isFalse(otherSession.isAlive?.());\n+          assert.isTrue(session.isAlive?.());\n+          assert.lengthOf(registeredPids, 1);\n+          assert.deepEqual(unregisteredPids, []);\n+\n+          const receivedDeltas: Array<string> = [];\n+          const firstDeltaGate = yield* Deferred.make<void>();\n+          const run = yield* session.send({\n+            message: \"hi\",\n+            onDelta: (update) =>\n+              Effect.gen(function* () {\n+                const text = (update as { readonly text?: string }).text ?? \"\";\n+                if (text === \"early-\") {\n+                  yield* Deferred.succeed(firstDeltaGate, undefined);\n+                }\n+                receivedDeltas.push(text);\n+              }),\n+          });\n+          assert.equal(run.runId, \"run-worker-1\");\n+          yield* Deferred.await(firstDeltaGate);\n+\n+          const steerOutcome = yield* run.steer!(\"change course\");\n+          assert.equal(steerOutcome, \"complete_delivered\");\n+\n+          const result = yield* run.wait;\n+          assert.equal(result.status, \"finished\");\n+          assert.equal(result.result, \"early-late\");\n+          assert.deepEqual(receivedDeltas, [\"early-\", \"late\"]);\n+\n+          const [messagesA, messagesB] = yield* Effect.all(\n+            [session.listMessages, session.listMessages],\n+            { concurrency: \"unbounded\" },\n+          );\n+          assert.lengthOf(messagesA, 1);\n+          assert.lengthOf(messagesB, 1);\n+          const usage = yield* session.readContextUsage!;\n+          assert.deepEqual(usage, { usedTokens: 120, maxTokens: 1000 });\n+          assert.isTrue(yield* session.runCheckpointed!(\"run-worker-1\"));\n+          assert.isFalse(yield* session.runCheckpointed!(\"other\"));\n+          yield* session.rewindAfterRun!(\"run-worker-1\");\n+          yield* session.close;\n+          assert.isFalse(session.isAlive?.());\n+\n+          assert.deepEqual(unregisteredPids, registeredPids);\n+          assert.deepEqual(stoppedUnits, [\"unit-cursor-sdk\"]);\n+          assert.include(protocolEvents, \"agent.open\");\n+          assert.include(protocolEvents, \"agent.opened\");\n+          assert.include(protocolEvents, \"run.started\");\n+          assert.include(protocolEvents, \"interaction.update\");\n+          assert.include(protocolEvents, \"run.completed\");\n+          assert.include(protocolEvents, \"agent.close\");\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"preserves ConfigurationError classification across IPC and cleans up on open failure\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          let unregistered = false;\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"config-error\" },\n+              registerProcess: () => () => {\n+                unregistered = true;\n+              },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const error = yield* Effect.flip(runner.open(openInput));\n+          assert.isTrue(isCursorSdkError(error.cause, \"ConfigurationError\"));\n+          assert.isTrue(\n+            error.cause instanceof Error &&\n+              error.cause.message.startsWith(\"Cannot use this model:\"),\n+          );\n+          assert.isTrue(unregistered);\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"fails run.wait with exit code and stderr when the worker crashes mid-run\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const unregistered = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"crash-mid-run\" },\n+            registerProcess: () => () => {\n+              Deferred.doneUnsafe(unregistered, Exit.void);\n+            },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+\n+        const session = yield* runner.open(openInput);\n+        const run = yield* session.send({ message: \"hi\" });\n+        const error = yield* Effect.flip(run.wait);\n+        const msg = CursorAgentSdk.cursorSdkFailureMessage(error);\n+        assert.include(msg, \"code 17\");\n+        assert.notInclude(msg, \"fatal worker boom\");\n+        const diagnostic = error.cause instanceof Error ? error.cause.cause : undefined;\n+        assert.isTrue(\n+          diagnostic instanceof Error && diagnostic.message.includes(\"fatal worker boom\"),\n+        );\n+        // Dead worker scope tears down immediately instead of waiting for sessions to close.\n+        yield* Deferred.await(unregistered);\n+        assert.isFalse(session.isAlive?.());\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"preserves an already-received runDone when the worker exits while onDelta is running\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const workerTerminated = yield* Deferred.make<void>();\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"exit-after-done\" },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+            onWorkerTerminated: () => {\n+              Deferred.doneUnsafe(workerTerminated, Exit.void);\n+            },\n+          });\n+\n+          const session = yield* runner.open(openInput);\n+          const deltaStarted = yield* Deferred.make<void>();\n+          const releaseDelta = yield* Deferred.make<void>();\n+          const run = yield* session.send({\n+            message: \"hi\",\n+            onDelta: (update) =>\n+              Effect.gen(function* () {\n+                if ((update as { readonly text?: string }).text === \"early-\") {\n+                  yield* Deferred.succeed(deltaStarted, undefined);\n+                  yield* Deferred.await(releaseDelta);\n+                }\n+              }),\n+          });\n+          yield* Deferred.await(deltaStarted);\n+          yield* Deferred.await(workerTerminated);\n+          yield* Deferred.succeed(releaseDelta, undefined);\n+          const result = yield* run.wait;\n+          assert.equal(result.status, \"finished\");\n+          assert.equal(result.result, \"early-late\");\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"cancels a started run when send is interrupted before handing it off\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const startedLogged = yield* Deferred.make<void>();\n+        const cancelled = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"cancel\" },\n+          }),\n+          protocolLoggerFor: () => (event) => {\n+            if (event.payload.type === \"run.started\") {\n+              return Deferred.succeed(startedLogged, undefined).pipe(Effect.andThen(Effect.never));\n+            }\n+            if (event.payload.type === \"run.cancel\" && event.direction === \"incoming\") {\n+              return Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid);\n+            }\n+            return Effect.void;\n+          },\n+        });\n+        const session = yield* runner.open(openInput);\n+        const sending = yield* Effect.forkChild(session.send({ message: \"hi\" }));\n+        yield* Deferred.await(startedLogged);\n+        yield* Fiber.interrupt(sending);\n+        yield* Deferred.await(cancelled);\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"closes the session when send is interrupted after transmission before acknowledgment\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const receivedByWorker = yield* Deferred.make<void>();\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"hang-send\" },\n+            }),\n+            protocolLoggerFor: () => (event) =>\n+              event.payload.type === \"run.started\"\n+                ? Deferred.succeed(receivedByWorker, undefined).pipe(Effect.asVoid)\n+                : Effect.void,\n+          });\n+\n+          const session = yield* runner.open(openInput);\n+          assert.isTrue(session.isAlive?.());\n+          const sending = yield* Effect.forkChild(session.send({ message: \"hi\" }));\n+          yield* Deferred.await(receivedByWorker);\n+          yield* Fiber.interrupt(sending);\n+          assert.isFalse(session.isAlive?.());\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"cancels an interrupted text generation in a worker that other sessions keep alive\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const received = yield* Deferred.make<void>();\n+        const cancelled = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"hang-text\" },\n+          }),\n+          protocolLoggerFor: () => (event) =>\n+            event.payload.type === \"run.started\"\n+              ? Deferred.succeed(received, undefined).pipe(Effect.asVoid)\n+              : event.payload.type === \"run.cancel\"\n+                ? Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid)\n+                : Effect.void,\n+        });\n+        const session = yield* runner.open(openInput);\n+        const generating = yield* Effect.forkChild(\n+          runner.textGenerate!({\n+            prompt: \"title\",\n+            apiKey: \"key\",\n+            model: { id: \"default\" },\n+            cwd: \"/tmp\",\n+            stateRoot: \"/tmp\",\n+          }),\n+        );\n+        yield* Deferred.await(received);\n+        yield* Fiber.interrupt(generating);\n+        yield* Deferred.await(cancelled);\n+        assert.isTrue(session.isAlive?.());\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"forwards cancel and runs textGenerate in a disposable child process\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+\n+        const cancelRunner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"cancel\" },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+        const session = yield* cancelRunner.open(openInput);\n+        const run = yield* session.send({ message: \"hi\" });\n+        yield* run.cancel;\n+        const cancelled = yield* run.wait;\n+        assert.equal(cancelled.status, \"cancelled\");\n+        yield* session.close;\n+\n+        let textGenUnregistered = false;\n+        const textGenRunner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"rate-limit-text\" },\n+            registerProcess: () => () => {\n+              textGenUnregistered = true;\n+            },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+        const textResult = yield* textGenRunner.textGenerate!({\n+          prompt: \"title\",\n+          apiKey: \"key\",\n+          model: { id: \"default\" },\n+          cwd: \"/tmp\",\n+          stateRoot: \"/tmp\",\n+        });\n+        assert.equal(textResult.status, \"error\");\n+        assert.isTrue(CursorAgentSdk.isCursorUsageLimitError(textResult.error));\n+        assert.isTrue(textGenUnregistered);\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"settles active runs on a closed session without disrupting peer sessions on the shared worker\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const registeredPids: Array<number> = [];\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"cancel\" },\n+              registerProcess: (pid) => {\n+                registeredPids.push(pid);\n+                return () => {};\n+              },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const sessionA = yield* runner.open(openInput);\n+          const sessionB = yield* runner.open({\n+            ...openInput,\n+            threadId: ThreadId.make(\"thread-worker-test-peer\"),\n+            providerSessionId: ProviderSessionId.make(\"provider-session-worker-test-peer\"),\n+          });\n+          assert.lengthOf(registeredPids, 1);\n+\n+          // Start a run on sessionA that stays pending, then close sessionA while sessionB keeps the worker alive.\n+          const runA = yield* sessionA.send({ message: \"hi\" });\n+          const waitA = yield* Effect.forkChild(Effect.flip(runA.wait));\n+          yield* sessionA.close;\n+          const errorA = yield* Fiber.join(waitA);\n+          assert.include(CursorAgentSdk.cursorSdkFailureMessage(errorA), \"closed\");\n+          assert.isFalse(sessionA.isAlive?.());\n+          assert.isTrue(sessionB.isAlive?.());\n+          assert.lengthOf(yield* sessionB.listMessages, 1);\n+          yield* sessionB.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"forwards background shell events across IPC, routes stop(), and ends orphans on worker crash\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"background-shell\" },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const events: Array<object> = [];\n+          const startedFirst = yield* Deferred.make<() => void>();\n+          const bothEnded = yield* Deferred.make<void>();\n+          let endedCount = 0;\n+\n+          const session = yield* runner.open(openInput);\n+          const run = yield* session.send({\n+            message: \"watch it\",\n+            onBackgroundShell: (event) =>\n+              Effect.gen(function* () {\n+                if (event.type === \"started\") {\n+                  const { stop, ...started } = event;\n+                  events.push(started);\n+                  if (event.id === \"sh-1\") yield* Deferred.succeed(startedFirst, stop);\n+                  return;\n+                }\n+                events.push(event);\n+                endedCount += 1;\n+                if (endedCount === 2) yield* Deferred.succeed(bothEnded, undefined);\n+              }),\n+          });\n+          yield* run.wait;\n+\n+          // Stopping sh-1 triggers a worker-side ended event, then the fake worker crashes to\n+          // verify sh-2 gets a synthesized ended(stopped: true) event.\n+          const stopFirst = yield* Deferred.await(startedFirst);\n+          stopFirst();\n+          yield* Deferred.await(bothEnded);\n+\n+          assert.deepEqual(events, [\n+            { type: \"started\", id: \"sh-1\", pid: 4101, command: \"sleep 60\" },\n+            { type: \"started\", id: \"sh-2\", pid: 4102, command: \"tail -f\" },\n+            {\n+              type: \"ended\",\n+              id: \"sh-1\",\n+              pid: 4101,\n+              command: \"sleep 60\",\n+              stopped: true,\n+              exitCode: undefined,\n+              outputPath: undefined,\n+            },\n+            {\n+              type: \"ended\",\n+              id: \"sh-2\",\n+              pid: 4102,\n+              command: \"tail -f\",\n+              stopped: true,\n+              exitCode: undefined,\n+              outputPath: undefined,\n+            },\n+          ]);\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+});\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts\nnew file mode 100644\nindex 0000000000..ed97c62288\n--- /dev/null\n+++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts\n@@ -0,0 +1,1167 @@\n+import type { AgentMessage, InteractionUpdate, RunResult, SteerAckOutcome } from \"@cursor/sdk\";\n+import * as ProviderEventLoggers from \"@t3tools/provider-core/server/ProviderEventLoggers\";\n+import { AgentScope } from \"@t3tools/shared/AgentScope\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n+import * as Cause from \"effect/Cause\";\n+import * as Deferred from \"effect/Deferred\";\n+import * as Duration from \"effect/Duration\";\n+import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n+import * as Fiber from \"effect/Fiber\";\n+import * as Layer from \"effect/Layer\";\n+import * as Option from \"effect/Option\";\n+import * as ChildProcess from \"effect/process/ChildProcess\";\n+import * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\n+import * as Queue from \"effect/Queue\";\n+import * as Ref from \"effect/Ref\";\n+import * as Scope from \"effect/Scope\";\n+import * as Semaphore from \"effect/Semaphore\";\n+import * as Stream from \"effect/Stream\";\n+\n+import * as CursorAgentSdk from \"./CursorAgentSdk.ts\";\n+import {\n+  type CursorWorkerMessage,\n+  type CursorWorkerRequest,\n+  type CursorWorkerResponsePayload,\n+  type SerializedRunResult,\n+  type SerializedRunnerFailure,\n+  decodeWorkerFrame,\n+  deserializeRunResult,\n+  deserializeWorkerError,\n+  encodeWorkerFrame,\n+} from \"./CursorAgentSdkWorkerProtocol.ts\";\n+\n+const WORKER_CLOSE_TIMEOUT = Duration.seconds(3);\n+const WORKER_EXIT_TIMEOUT = Duration.seconds(2);\n+const MAX_STDERR_CHARS = 8_192;\n+\n+export interface CursorSdkWorkerLaunch {\n+  readonly command: string;\n+  readonly args: ReadonlyArray<string>;\n+  readonly env?: NodeJS.ProcessEnv | undefined;\n+  readonly registerProcess?: ((pid: number) => () => void) | undefined;\n+}\n+\n+type RunQueueItem =\n+  | { readonly _tag: \"delta\"; readonly update: InteractionUpdate }\n+  | { readonly _tag: \"done\"; readonly ok: true; readonly result: RunResult }\n+  | {\n+      readonly _tag: \"done\";\n+      readonly ok: false;\n+      readonly error: CursorAgentSdk.CursorAgentSdkRunnerError;\n+    };\n+\n+interface ActiveWorkerRun {\n+  readonly sessionId: number;\n+  readonly queue: Queue.Queue<RunQueueItem>;\n+  readonly waitDeferred: Deferred.Deferred<RunResult, CursorAgentSdk.CursorAgentSdkRunnerError>;\n+  doneEnqueued: boolean;\n+}\n+\n+function toRunnerError(method: string, cause: unknown): CursorAgentSdk.CursorAgentSdkRunnerError {\n+  return CursorAgentSdk.isCursorAgentSdkRunnerError(cause)\n+    ? cause\n+    : new CursorAgentSdk.CursorAgentSdkRunnerError({ method, cause });\n+}\n+\n+function fromSerializedFailure(\n+  failure: SerializedRunnerFailure,\n+): CursorAgentSdk.CursorAgentSdkRunnerError {\n+  return new CursorAgentSdk.CursorAgentSdkRunnerError({\n+    method: failure.method,\n+    cause: deserializeWorkerError(failure.cause),\n+  });\n+}\n+\n+function workerExitError(method: string, exitCode: number | undefined, stderr: string) {\n+  const trimmedStderr = stderr.trim();\n+  const detail = `Cursor SDK worker exited unexpectedly${exitCode === undefined ? \"\" : ` (code ${exi",
      "stagedSummary": " apps/server/package.json                           |    2 +-\n apps/server/src/binMain.ts                         |    6 +\n ...viderOrchestrationAdapterInfrastructure.test.ts |   37 +\n .../ProviderOrchestrationAdapterInfrastructure.ts  |   36 +-\n packages/provider-cursor/package.json              |   10 +-\n .../src/server/CursorAgentSdk.test.ts              |  104 +-\n .../provider-cursor/src/server/CursorAgentSdk.ts   |  235 +++-\n .../src/server/CursorAgentSdkProcessRunner.test.ts |  742 +++++++++++++\n .../src/server/CursorAgentSdkProcessRunner.ts      | 1167 ++++++++++++++++++++\n .../src/server/CursorAgentSdkWorker.ts             |  647 +++++++++++\n .../src/server/CursorAgentSdkWorkerProtocol.ts     |  304 +++++\n .../provider-cursor/src/server/adapter.test.ts     |  137 +++\n packages/provider-cursor/src/server/adapter.ts     |    3 +-\n packages/provider-cursor/src/server/driver.ts      |    1 +\n packages/provider-cursor/src/server/sdk.ts         |   42 +-\n .../src/server/textGeneration.test.ts              |   37 +\n .../provider-cursor/src/server/textGeneration.ts   |  279 +++--\n ...r__sdk@1.4.1.patch => @cursor__sdk@1.4.2.patch} |  101 +-\n pnpm-lock.yaml                                     |   58 +-\n pnpm-workspace.yaml                                |    4 +-\n 20 files changed, 3727 insertions(+), 225 deletions(-)\n"
    }
  },
  {
    "side": "after",
    "results": [
      {
        "side": "after",
        "run": 1,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825755796,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825758840,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825765664,
            "event": "run.result",
            "result": {
              "id": "run-8cc9081c-27cd-400a-a605-bee1403ea25a",
              "requestId": "3cab08ed-0406-4832-b5ba-923cf3c39afd",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 6326,
              "usage": {
                "inputTokens": 15011,
                "outputTokens": 323,
                "cacheReadTokens": 896,
                "cacheWriteTokens": 0,
                "totalTokens": 15334,
                "reasoningTokens": 250
              }
            }
          },
          {
            "time": 1795825765665,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes.\n\nThe commit message must be a JSON object with subject and body keys.\n\nThe primary change is moving the Cursor Agent SDK out-of-process via a new worker process. The CLI now has a fast path for this worker, and provider orchestration uses ProcessRunner instead of in-process execution. A shared SqliteLocalAgentStore with ref-counting per workspace was added, along with textGenerate support and an SDK bump from 1.4.1 to 1.4.2.",
                        "thinkingDurationMs": 3941
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825765843,
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker CLI, protocol, and process runner\n- Share ref-counted workspace SQLite stores with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 10091
      },
      {
        "side": "after",
        "run": 2,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825765873,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825766602,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825773856,
            "event": "run.result",
            "result": {
              "id": "run-6881cc21-bdc8-451c-a501-968d59da16b7",
              "requestId": "9b7d7cb5-d854-4269-b82c-a71d2e358068",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI entry\\n- Ref-count shared SqliteLocalAgentStore per workspace; noop runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 6932,
              "usage": {
                "inputTokens": 15005,
                "outputTokens": 330,
                "cacheReadTokens": 896,
                "cacheWriteTokens": 0,
                "totalTokens": 15335,
                "reasoningTokens": 247
              }
            }
          },
          {
            "time": 1795825773856,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes, and return a JSON object with keys `subject` and `body`.\n\nThe changes upgrade `@cursor/sdk`.\n\nThe primary change runs the Cursor Agent SDK out-of-process via a new worker. The adapter switches to ProcessRunner. Workspace SQLite ref-counting and noop runEvents reduce bloat and locks. Text generation updates and tests accompany these changes.",
                        "thinkingDurationMs": 2171
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI entry\\n- Ref-count shared SqliteLocalAgentStore per workspace; noop runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825774003,
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker, process runner, and __cursor-sdk-worker CLI entry\n- Ref-count shared SqliteLocalAgentStore per workspace; noop runEvents appends\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 8148
      },
      {
        "side": "after",
        "run": 3,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825774025,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825775246,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825780192,
            "event": "run.result",
            "result": {
              "id": "run-8644fa5b-9e5a-4e6c-b8da-5053e1dd51d7",
              "requestId": "e205cc1d-e47b-4ccd-96a0-8c27fcdac5f8",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor agent SDK in an out-of-process worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI and NDJSON process runner\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 4649,
              "usage": {
                "inputTokens": 15011,
                "outputTokens": 305,
                "cacheReadTokens": 896,
                "cacheWriteTokens": 0,
                "totalTokens": 15316,
                "reasoningTokens": 230
              }
            }
          },
          {
            "time": 1795825780192,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes, and return a JSON object with keys `subject` and `body`.\n\nThe changes include upgrading `@cursor/sdk`.\n\nThe Cursor agent SDK is now isolated in an out-of-process worker. The server CLI gains a `__cursor-sdk-worker` fast path. Provider orchestration uses the process runner instead of the in-process SDK. A shared ref-counted SqliteLocalAgentStore with noop runEvents was added. Text generation and tests were updated.",
                        "thinkingDurationMs": 2571
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor agent SDK in an out-of-process worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI and NDJSON process runner\\n- Share ref-counted workspace SQLite stores with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825780362,
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor agent SDK in an out-of-process worker",
              "body": "- Add __cursor-sdk-worker CLI and NDJSON process runner\n- Share ref-counted workspace SQLite stores with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 6350
      },
      {
        "side": "after",
        "run": 4,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825780382,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825781078,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825787619,
            "event": "run.result",
            "result": {
              "id": "run-09b06878-d341-47f6-abab-e2f4b5b4ca2c",
              "requestId": "70460c86-6b67-47a5-97f9-d5d99adacdd1",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK out of process via worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI and NDJSON ProcessRunner/Worker protocol\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 6262,
              "usage": {
                "inputTokens": 15011,
                "outputTokens": 315,
                "cacheReadTokens": 896,
                "cacheWriteTokens": 0,
                "totalTokens": 15326,
                "reasoningTokens": 238
              }
            }
          },
          {
            "time": 1795825787619,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes.\n\nThe commit message must be a JSON object with keys `subject` and `body`.\n\nThe staged changes upgrade @cursor/sdk to 1.4.2. They introduce an out-of-process Cursor SDK worker and related process runner and protocol classes. The adapter now uses the new process runner instead of in-process execution. Workspace SQLite stores get ref-counting and no-op runEvents to avoid bloat and locks. Text generation is updated for out-of-process support.\n\nThe subject is drafted as \"Run Cursor Agent SDK in an out-of-process worker\". The body will list the key changes.",
                        "thinkingDurationMs": 3676
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK out of process via worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI and NDJSON ProcessRunner/Worker protocol\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825787812,
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK out of process via worker",
              "body": "- Add __cursor-sdk-worker CLI and NDJSON ProcessRunner/Worker protocol\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 7440
      },
      {
        "side": "after",
        "run": 5,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825787825,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825788527,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825795394,
            "event": "run.result",
            "result": {
              "id": "run-16458660-32c1-41a5-9ba8-f54b6f9ce7cd",
              "requestId": "5ba17608-79e1-439f-94c0-68d752671ef9",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor agent SDK in an out-of-process worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI path and NDJSON process runner\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 6555,
              "usage": {
                "inputTokens": 15008,
                "outputTokens": 339,
                "cacheReadTokens": 896,
                "cacheWriteTokens": 0,
                "totalTokens": 15347,
                "reasoningTokens": 261
              }
            }
          },
          {
            "time": 1795825795395,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes, and return a JSON object with keys `subject` and `body`.\n\nThe changes upgrade `@cursor/sdk` from version 1.\n\nThe upgrade is from 1.4.1 to 1.4.2. The main change moves the Cursor agent SDK into an out-of-process worker process. This includes a new `CursorAgentSdkWorker`, `CursorAgentSdkProcessRunner`, and protocol. A `__cursor-sdk-worker` CLI fast path was added to `binMain`. `ProviderOrchestrationAdapterInfrastructure` now uses the process runner instead of the in-process SDK. Workspace SQLite stores are ref-counted per workspace with no-op run events to prevent bloat and locks. Text generation was updated for out-of-process support.",
                        "thinkingDurationMs": 3838
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor agent SDK in an out-of-process worker\",\n  \"body\": \"- Add __cursor-sdk-worker CLI path and NDJSON process runner\\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825795528,
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor agent SDK in an out-of-process worker",
              "body": "- Add __cursor-sdk-worker CLI path and NDJSON process runner\n- Share ref-counted SqliteLocalAgentStore per workspace with noop runEvents\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 7711
      },
      {
        "side": "after",
        "run": 6,
        "sha": "ab3079cc55a5c40c0cbd1e2e2d6d2af81868132c",
        "patchBytes": 60000,
        "events": [
          {
            "time": 1795825795545,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": true
          },
          {
            "time": 1795825796273,
            "event": "Agent.create",
            "mode": "agent",
            "tools": [],
            "model": {
              "id": "default"
            },
            "sandbox": false
          },
          {
            "time": 1795825803271,
            "event": "run.result",
            "result": {
              "id": "run-132ba42f-db23-460d-be2c-58eb37c8ac64",
              "requestId": "8356881e-9ae6-4e83-973d-0d821b390a20",
              "status": "finished",
              "result": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner; wire orchestration to spawn it\\n- Ref-count shared SqliteLocalAgentStore per workspace with noop runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```",
              "model": {
                "id": "default"
              },
              "durationMs": 6575,
              "usage": {
                "inputTokens": 15008,
                "outputTokens": 303,
                "cacheReadTokens": 896,
                "cacheWriteTokens": 0,
                "totalTokens": 15311,
                "reasoningTokens": 220
              }
            }
          },
          {
            "time": 1795825803271,
            "event": "run.conversation",
            "conversation": [
              {
                "type": "agentConversationTurn",
                "turn": {
                  "steps": [
                    {
                      "type": "thinkingMessage",
                      "message": {
                        "text": "The user wants me to write a concise git commit message based on the staged changes, and return a JSON object with keys: subject and body.\n\nThe changes include an upgrade to @cursor/sdk.\n\nThe upgrade bumps @cursor/sdk from 1.4.1 to 1.4.2. The main change is moving the Cursor Agent SDK out-of-process via a dedicated worker process and CLI fast path. Provider orchestration now uses the process runner instead of in-process execution. Workspace stores share a ref-counted SqliteLocalAgentStore with noop runEvents. Text generation and tests were also updated.",
                        "thinkingDurationMs": 4007
                      }
                    },
                    {
                      "type": "assistantMessage",
                      "message": {
                        "text": "```json\n{\n  \"subject\": \"Run Cursor Agent SDK in an out-of-process worker\",\n  \"body\": \"- Add NDJSON worker CLI, protocol, and process runner; wire orchestration to spawn it\\n- Ref-count shared SqliteLocalAgentStore per workspace with noop runEvents appends\\n- Bump @cursor/sdk to 1.4.2\"\n}\n```"
                      }
                    }
                  ]
                }
              }
            ]
          },
          {
            "time": 1795825803424,
            "event": "generation.success",
            "result": {
              "subject": "Run Cursor Agent SDK in an out-of-process worker",
              "body": "- Add NDJSON worker CLI, protocol, and process runner; wire orchestration to spawn it\n- Ref-count shared SqliteLocalAgentStore per workspace with noop runEvents appends\n- Bump @cursor/sdk to 1.4.2"
            }
          }
        ],
        "success": true,
        "elapsedMs": 7888
      }
    ],
    "input": {
      "stagedPatch": "diff --git a/apps/server/package.json b/apps/server/package.json\nindex e9f211891a..8ece0aaa81 100644\n--- a/apps/server/package.json\n+++ b/apps/server/package.json\n@@ -37,7 +37,7 @@\n   },\n   \"dependencies\": {\n     \"@anthropic-ai/claude-agent-sdk\": \"^0.3.321\",\n-    \"@cursor/sdk\": \"1.4.1\",\n+    \"@cursor/sdk\": \"1.4.2\",\n     \"@effect/platform-node\": \"catalog:\",\n     \"@effect/platform-node-shared\": \"catalog:\",\n     \"@ff-labs/fff-node\": \"0.11.0\",\ndiff --git a/apps/server/src/binMain.ts b/apps/server/src/binMain.ts\nindex 0dabd73873..7d4c93fb04 100644\n--- a/apps/server/src/binMain.ts\n+++ b/apps/server/src/binMain.ts\n@@ -30,6 +30,12 @@ export async function runCliCommand() {\n     if (mode !== \"discover\" && mode !== \"model\") throw new Error(\"Unknown speech worker mode.\");\n     const { runNativeSpeechWorker } = await import(\"./speech/native.ts\");\n     await runNativeSpeechWorker(mode, process.argv[4]);\n+  } else if (command === \"__cursor-sdk-worker\") {\n+    const [NodeServices, { runCursorSdkWorker }] = await Promise.all([\n+      import(\"@effect/platform-node/NodeServices\"),\n+      import(\"@t3tools/provider-cursor/server/worker\"),\n+    ]);\n+    await runCursorSdkWorker(NodeServices.layer);\n   } else {\n     enableCliCompileCache();\n     // Windows desktop launches without stdin; attach before reading, except on fast paths using pipes.\ndiff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\nindex 8458b46b30..981f6847ef 100644\n--- a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\n+++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts\n@@ -1,8 +1,14 @@\n+import * as NodeServices from \"@effect/platform-node/NodeServices\";\n import { assert, it } from \"@effect/vitest\";\n import { ProviderDriverKind } from \"@t3tools/contracts\";\n import * as IdAllocator from \"@t3tools/provider-core/server/IdAllocator\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n import * as Effect from \"effect/Effect\";\n import * as Layer from \"effect/Layer\";\n+import * as Path from \"effect/Path\";\n+import * as ChildProcess from \"effect/process/ChildProcess\";\n+import * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\n+import * as Stream from \"effect/Stream\";\n import * as SqlClient from \"effect/sql/SqlClient\";\n \n import * as SqlitePersistence from \"../persistence/Sqlite.ts\";\n@@ -40,3 +46,34 @@ it.effect(\"subagent threads stored under a legacy id keep it when re-derived\", (\n     );\n   }),\n );\n+\n+it.live(\"spawns the __cursor-sdk-worker CLI fast path and shuts down cleanly on close\", () =>\n+  Effect.scoped(\n+    Effect.gen(function* () {\n+      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n+      const path = yield* Path.Path;\n+      const executable = yield* HostProcess.ExecutablePath;\n+      const entry = yield* path.fromFileUrl(new URL(\"../bin.ts\", import.meta.url));\n+      const handle = yield* spawner.spawn(\n+        ChildProcess.make(executable, [entry, \"__cursor-sdk-worker\"], {\n+          stdin: { stream: \"pipe\", endOnDone: false },\n+          stdout: \"pipe\",\n+          stderr: \"pipe\",\n+        }),\n+      );\n+      yield* Stream.run(\n+        Stream.encodeText(Stream.make(`${JSON.stringify({ id: 1, type: \"close\" })}\\n`)),\n+        handle.stdin,\n+      );\n+      const stdout = yield* handle.stdout.pipe(Stream.decodeText(), Stream.mkString);\n+      const exitCode = Number(yield* handle.exitCode);\n+      assert.strictEqual(exitCode, 0);\n+      assert.deepStrictEqual(JSON.parse(stdout.trim()), {\n+        type: \"response\",\n+        id: 1,\n+        ok: true,\n+        result: null,\n+      });\n+    }),\n+  ).pipe(Effect.provide(NodeServices.layer)),\n+);\ndiff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\nindex b01735a7c2..ffb25e7daa 100644\n--- a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\n+++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts\n@@ -1,13 +1,17 @@\n import * as Effect from \"effect/Effect\";\n import * as Layer from \"effect/Layer\";\n+import * as Path from \"effect/Path\";\n import * as SqlClient from \"effect/sql/SqlClient\";\n \n import * as ClaudeAdapterV2 from \"../orchestration-v2/Adapters/ClaudeAdapterV2.ts\";\n import * as CodexAdapterV2 from \"../orchestration-v2/Adapters/CodexAdapterV2.ts\";\n-import * as CursorAgentSdk from \"@t3tools/provider-cursor/server/CursorAgentSdk\";\n+import * as ProviderProcesses from \"../process/providerProcesses.ts\";\n+import type * as CursorAgentSdk from \"@t3tools/provider-cursor/server/CursorAgentSdk\";\n+import * as CursorAgentSdkProcessRunner from \"@t3tools/provider-cursor/server/CursorAgentSdkProcessRunner\";\n import * as CursorSdk from \"@t3tools/provider-cursor/server/CursorSdk\";\n import * as IdAllocator from \"@t3tools/provider-core/server/IdAllocator\";\n import * as ProviderContinuationRequests from \"@t3tools/provider-core/server/ProviderContinuationRequests\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n \n export type ProviderOrchestrationAdapterInfrastructure =\n   | ClaudeAdapterV2.ClaudeAgentSdkQueryRunner\n@@ -34,11 +38,39 @@ export const layerIdAllocator = Layer.unwrap(\n   }),\n );\n \n+const resolveCursorWorkerLaunch = Effect.gen(function* () {\n+  const path = yield* Path.Path;\n+  const command = yield* HostProcess.ExecutablePath;\n+  const isExecutable = yield* HostProcess.IsExecutable;\n+  const providerProcesses = yield* ProviderProcesses.ProviderProcesses;\n+  // In a bundle import.meta.url is bin.mjs; development and tests use this source module.\n+  const entry = yield* path\n+    .fromFileUrl(\n+      new URL(import.meta.url.endsWith(\".ts\") ? \"../bin.ts\" : \"./bin.mjs\", import.meta.url),\n+    )\n+    .pipe(Effect.orDie);\n+  return {\n+    command,\n+    args: [...(isExecutable ? [] : [entry]), \"__cursor-sdk-worker\"],\n+    ...(providerProcesses.register === undefined\n+      ? {}\n+      : { registerProcess: providerProcesses.register }),\n+  };\n+});\n+\n /** Reuse the continuation worker's exact layer reference so memoization shares one queue. */\n export const layer = Layer.mergeAll(\n   ClaudeAdapterV2.layerQueryRunner,\n   CodexAdapterV2.layerAppServerClientFactory,\n-  CursorAgentSdk.layer.pipe(Layer.provideMerge(CursorSdk.layer)),\n+  Layer.unwrap(\n+    Effect.gen(function* () {\n+      const path = yield* Path.Path;\n+      return CursorAgentSdkProcessRunner.layer(\n+        resolveCursorWorkerLaunch.pipe(Effect.provideService(Path.Path, path)),\n+      );\n+    }),\n+  ),\n+  CursorSdk.layer,\n   layerIdAllocator,\n   ProviderContinuationRequests.layer,\n );\ndiff --git a/packages/provider-cursor/package.json b/packages/provider-cursor/package.json\nindex e1d101a92f..dcd6bd0904 100644\n--- a/packages/provider-cursor/package.json\n+++ b/packages/provider-cursor/package.json\n@@ -23,6 +23,14 @@\n       \"types\": \"./src/server/CursorAgentSdk.ts\",\n       \"import\": \"./src/server/CursorAgentSdk.ts\"\n     },\n+    \"./server/CursorAgentSdkProcessRunner\": {\n+      \"types\": \"./src/server/CursorAgentSdkProcessRunner.ts\",\n+      \"import\": \"./src/server/CursorAgentSdkProcessRunner.ts\"\n+    },\n+    \"./server/worker\": {\n+      \"types\": \"./src/server/CursorAgentSdkWorker.ts\",\n+      \"import\": \"./src/server/CursorAgentSdkWorker.ts\"\n+    },\n     \"./server/accountUsage\": {\n       \"types\": \"./src/server/accountUsage.ts\",\n       \"import\": \"./src/server/accountUsage.ts\"\n@@ -45,7 +53,7 @@\n     \"test\": \"vp test run --config ../../vite.config.ts --dir .\"\n   },\n   \"dependencies\": {\n-    \"@cursor/sdk\": \"1.4.1\",\n+    \"@cursor/sdk\": \"1.4.2\",\n     \"@t3tools/contracts\": \"workspace:*\",\n     \"@t3tools/provider-core\": \"workspace:*\",\n     \"@t3tools/shared\": \"workspace:*\",\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\nindex 187ce35990..94ae520513 100644\n--- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\n+++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts\n@@ -60,7 +60,7 @@ const cursorSdkMock = vi.hoisted(() => {\n       };\n     },\n   );\n-  const create = vi.fn(async () => ({\n+  const create = vi.fn(async (_options?: unknown) => ({\n     agentId: \"agent-cursor-agent-sdk-test\",\n     send,\n     close: agentClose,\n@@ -87,6 +87,8 @@ const cursorSdkMock = vi.hoisted(() => {\n     );\n   });\n \n+  const sqliteOpen = vi.fn<() => Promise<unknown>>(async () => undefined);\n+\n   return {\n     agentClose,\n     cancelRun,\n@@ -99,6 +101,7 @@ const cursorSdkMock = vi.hoisted(() => {\n     runSteer,\n     runWait,\n     send,\n+    sqliteOpen,\n     setAgentCloseFailure: (failure: unknown) => {\n       agentCloseFailure = failure;\n     },\n@@ -121,7 +124,7 @@ vi.mock(\"./sdk.ts\", () => ({\n     },\n     createAgentPlatform: vi.fn(),\n   }),\n-  loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: vi.fn() } }),\n+  loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: cursorSdkMock.sqliteOpen } }),\n }));\n \n const layerTest = CursorAgentSdk.layer.pipe(\n@@ -509,4 +512,101 @@ describe(\"CursorAgentSdkRunner\", () => {\n       assert.equal(yield* plain.steer!(\"later\"), \"revert_to_followup\");\n     }).pipe(Effect.provide(layerTest)),\n   );\n+\n+  it.effect(\n+    \"ref-counts one disposable SqliteLocalAgentStore with no-op runEvents per workspace\",\n+    () =>\n+      Effect.gen(function* () {\n+        const dispose = vi.fn(async () => {});\n+        const underlyingAppend = vi.fn(async () => {\n+          throw new Error(\"runEvents.append must not hit SQLite\");\n+        });\n+        const fakeStore = {\n+          agents: { get: vi.fn() },\n+          runs: { list: vi.fn() },\n+          checkpoints: { save: vi.fn() },\n+          runEvents: { append: underlyingAppend, list: vi.fn(), delete: vi.fn() },\n+          dispose,\n+        };\n+        cursorSdkMock.sqliteOpen.mockClear();\n+        cursorSdkMock.sqliteOpen.mockResolvedValueOnce(fakeStore);\n+        cursorSdkMock.create.mockClear();\n+\n+        const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;\n+        const session = yield* runner.open({\n+          operation: \"create\",\n+          options: { local: { cwd: \"/workspace/cursor-store-test\" } },\n+          threadId: ThreadId.make(\"thread-cursor-agent-sdk-store\"),\n+          providerSessionId: ProviderSessionId.make(\"provider-session-cursor-agent-sdk-store\"),\n+        });\n+        const peer = yield* runner.open({\n+          operation: \"create\",\n+          options: { local: { cwd: \"/workspace/cursor-store-test\" } },\n+          threadId: ThreadId.make(\"thread-cursor-agent-sdk-store-peer\"),\n+          providerSessionId: ProviderSessionId.make(\"provider-session-cursor-agent-sdk-store-peer\"),\n+        });\n+\n+        assert.deepStrictEqual(cursorSdkMock.sqliteOpen.mock.calls, [\n+          [{ workspaceRef: \"/workspace/cursor-store-test\" }],\n+        ]);\n+        const passedOptions = cursorSdkMock.create.mock.calls[0]?.[0] as\n+          | {\n+              readonly local?: {\n+                readonly store?: {\n+                  readonly agents: unknown;\n+                  readonly checkpoints: unknown;\n+                  readonly runEvents: {\n+                    readonly append: (event: {\n+                      readonly runId: string;\n+                      readonly eventType: string;\n+                      readonly payload?: unknown;\n+                    }) => Promise<{ readonly seq: number }>;\n+                  };\n+                };\n+              };\n+            }\n+          | undefined;\n+        const peerOptions = cursorSdkMock.create.mock.calls[1]?.[0] as typeof passedOptions;\n+        const passedStore = passedOptions?.local?.store;\n+        assert.isDefined(passedStore);\n+        assert.strictEqual(peerOptions?.local?.store, passedStore);\n+        assert.strictEqual(passedStore?.agents, fakeStore.agents);\n+        assert.strictEqual(passedStore?.checkpoints, fakeStore.checkpoints);\n+        const appended = yield* Effect.promise(() =>\n+          passedStore!.runEvents.append({\n+            runId: \"run-1\",\n+            eventType: \"text-delta\",\n+            payload: { text: \"hi\" },\n+          }),\n+        );\n+        assert.equal(appended.seq, 1);\n+        assert.equal(underlyingAppend.mock.calls.length, 0);\n+        assert.equal(dispose.mock.calls.length, 0);\n+\n+        // Closing one session keeps the shared workspace store alive; repeated close does not double-release.\n+        yield* session.close;\n+        yield* session.close;\n+        assert.equal(dispose.mock.calls.length, 0);\n+\n+        yield* peer.close;\n+        assert.equal(dispose.mock.calls.length, 1);\n+\n+        // Failed open disposes the newly opened store instead of leaking SQLite FDs.\n+        const failingDispose = vi.fn(async () => {});\n+        cursorSdkMock.sqliteOpen.mockResolvedValueOnce({ ...fakeStore, dispose: failingDispose });\n+        cursorSdkMock.create.mockRejectedValueOnce(new Error(\"boom\"));\n+        const failed = yield* runner\n+          .open({\n+            operation: \"create\",\n+            options: { local: { cwd: \"/workspace/cursor-store-fail\" } },\n+            threadId: ThreadId.make(\"thread-cursor-agent-sdk-store-fail\"),\n+            providerSessionId: ProviderSessionId.make(\n+              \"provider-session-cursor-agent-sdk-store-fail\",\n+            ),\n+          })\n+          .pipe(Effect.exit);\n+        assert(Exit.isFailure(failed));\n+        assert.equal(failingDispose.mock.calls.length, 1);\n+      }).pipe(Effect.provide(layerTest)),\n+  );\n });\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts\nindex 75b0232ebf..81b8208a5d 100644\n--- a/packages/provider-cursor/src/server/CursorAgentSdk.ts\n+++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts\n@@ -18,10 +18,12 @@ import {\n import * as Context from \"effect/Context\";\n import * as Deferred from \"effect/Deferred\";\n import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n import * as Layer from \"effect/Layer\";\n import * as Option from \"effect/Option\";\n import * as Ref from \"effect/Ref\";\n import * as Schema from \"effect/Schema\";\n+import * as Semaphore from \"effect/Semaphore\";\n \n import * as CursorSdk from \"./CursorSdk.ts\";\n import * as ProviderEventLoggers from \"@t3tools/provider-core/server/ProviderEventLoggers\";\n@@ -165,9 +167,19 @@ export interface CursorAgentSdkSession {\n    * The open agent keeps its old conversation in memory, so reopen it before the next send.\n    */\n   readonly rewindAfterRun?: (runId: string) => Effect.Effect<void, CursorAgentSdkRunnerError>;\n+  /** False once an out-of-process worker has terminated or started closing; absent on in-process sessions. */\n+  readonly isAlive?: () => boolean;\n   readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;\n }\n \n+export interface CursorAgentSdkTextGenerateInput {\n+  readonly prompt: string;\n+  readonly apiKey: string;\n+  readonly model: NonNullable<AgentOptions[\"model\"]>;\n+  readonly cwd: string;\n+  readonly stateRoot: string;\n+}\n+\n export class CursorAgentSdkRunner extends Context.Service<\n   CursorAgentSdkRunner,\n   {\n@@ -175,6 +187,10 @@ export class CursorAgentSdkRunner extends Context.Service<\n       input: CursorAgentSdkOpenInput,\n     ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;\n     readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;\n+    /** Absent on in-process test doubles; the out-of-process runner provides it. */\n+    readonly textGenerate?: (\n+      input: CursorAgentSdkTextGenerateInput,\n+    ) => Effect.Effect<RunResult, CursorAgentSdkRunnerError>;\n   }\n >()(\"@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner\") {}\n \n@@ -414,7 +430,7 @@ export function loggedCursorSendOptions(\n   };\n }\n \n-function makeCursorAgentSdkProtocolLogger(input: {\n+export function makeCursorAgentSdkProtocolLogger(input: {\n   readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;\n   readonly threadId: ThreadId;\n   readonly providerSessionId: OrchestrationV2ProviderSession[\"id\"];\n@@ -463,6 +479,60 @@ function subscribeShellStreamOutput(listener: (output: CursorShellStreamOutput)\n   };\n }\n \n+type CursorLocalStore = NonNullable<NonNullable<AgentOptions[\"local\"]>[\"store\"]>;\n+\n+interface DisposableCursorLocalStore extends CursorLocalStore {\n+  readonly dispose: () => Promise<void>;\n+}\n+\n+function isDisposableCursorLocalStore(value: unknown): value is DisposableCursorLocalStore {\n+  return (\n+    typeof value === \"object\" &&\n+    value !== null &&\n+    \"agents\" in value &&\n+    \"runs\" in value &&\n+    \"checkpoints\" in value &&\n+    \"runEvents\" in value &&\n+    \"dispose\" in value &&\n+    typeof value.dispose === \"function\"\n+  );\n+}\n+\n+// T3 persists its own event log and never tails SDK run_events; skipping per-delta SQLite\n+// run_events writes avoids synchronous BEGIN IMMEDIATE write locks and multi-GB index.db bloat.\n+export function withNoopCursorRunEvents(store: CursorLocalStore): CursorLocalStore {\n+  if (\n+    typeof store !== \"object\" ||\n+    store === null ||\n+    typeof store.runEvents?.append !== \"function\"\n+  ) {\n+    return store;\n+  }\n+  let seq = 0;\n+  return {\n+    agents: store.agents,\n+    runs: store.runs,\n+    checkpoints: store.checkpoints,\n+    runEvents: {\n+      append: async (event) => {\n+        seq += 1;\n+        return {\n+          runId: event.runId,\n+          seq,\n+          offset: String(seq),\n+          eventType: event.eventType,\n+          payload: event.payload ?? null,\n+          payloadRef: event.payloadRef ?? null,\n+          idempotencyKey: event.idempotencyKey ?? null,\n+          createdAt: 0,\n+        };\n+      },\n+      list: async () => ({ items: [] }),\n+      delete: async () => {},\n+    },\n+  };\n+}\n+\n interface CursorBackgroundShell {\n   readonly conversationId?: unknown;\n   readonly command?: unknown;\n@@ -548,6 +618,58 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n     },\n   );\n \n+  // Ref-count one SqliteLocalAgentStore per workspace so concurrent sessions share a single\n+  // index.db handle while still disposing handles, page caches, and FDs once the last one closes.\n+  interface WorkspaceStoreLease {\n+    readonly store: DisposableCursorLocalStore;\n+    readonly wrapped: CursorLocalStore;\n+    users: number;\n+  }\n+  const workspaceStores = new Map<string, WorkspaceStoreLease>();\n+  const workspaceStoreLock = yield* Semaphore.make(1);\n+  const acquireWorkspaceStore = (workspaceRef: string, method: string) =>\n+    workspaceStoreLock.withPermits(1)(\n+      Effect.suspend(() => {\n+        const existing = workspaceStores.get(workspaceRef);\n+        if (existing !== undefined) {\n+          existing.users += 1;\n+          return Effect.succeed(existing);\n+        }\n+        return Effect.tryPromise({\n+          try: async () => {\n+            const candidate = await sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef });\n+            return isDisposableCursorLocalStore(candidate) ? candidate : undefined;\n+          },\n+          catch: (cause) => runnerError(cause, method),\n+        }).pipe(\n+          Effect.map((opened) => {\n+            if (opened === undefined) return undefined;\n+            const lease: WorkspaceStoreLease = {\n+              store: opened,\n+              wrapped: withNoopCursorRunEvents(opened),\n+              users: 1,\n+            };\n+            workspaceStores.set(workspaceRef, lease);\n+            return lease;\n+          }),\n+        );\n+      }),\n+    );\n+  const releaseWorkspaceStore = (workspaceRef: string, lease: WorkspaceStoreLease) =>\n+    workspaceStoreLock.withPermits(1)(\n+      Effect.suspend(() => {\n+        lease.users -= 1;\n+        if (lease.users > 0) return Effect.void;\n+        if (workspaceStores.get(workspaceRef) === lease) {\n+          workspaceStores.delete(workspaceRef);\n+        }\n+        return Effect.tryPromise({\n+          try: () => lease.store.dispose(),\n+          catch: () => undefined,\n+        }).pipe(Effect.ignore);\n+      }),\n+    );\n+\n   return CursorAgentSdkRunner.of({\n     open: Effect.fn(\"CursorAgentSdkRunner.open\")(function* (input) {\n       const { Agent, createAgentPlatform } = yield* Effect.try({\n@@ -573,59 +695,85 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n       });\n \n       // Cursor uses cwd for both execution and store lookup; a moved thread keeps its original store.\n-      const storeCwd = input.storeCwd;\n-      const storePlatform =\n-        input.operation === \"resume\" &&\n-        storeCwd !== undefined &&\n-        storeCwd !== input.options.local?.cwd\n-          ? yield* Effect.tryPromise({\n-              try: () =>\n-                createAgentPlatform({\n-                  workspaceRef: storeCwd,\n-                  ...(input.options.local?.store === undefined\n-                    ? {}\n-                    : { localStore: input.options.local.store }),\n-                }),\n-              catch: (cause) => runnerError(cause, \"agent.resume\"),\n-            })\n-          : undefined;\n-      const agent = yield* Effect.tryPromise({\n-        try: () =>\n-          input.operation === \"create\"\n-            ? Agent.create(input.options)\n-            : storePlatform === undefined\n-              ? Agent.resume(input.agentId!, input.options)\n-              : storePlatform.resumeAgent(input.agentId!, input.options),\n-        catch: (cause) => runnerError(cause, `agent.${input.operation}`),\n-      });\n-      let shellListener: ((event: CursorBackgroundShellEvent) => void) | undefined;\n-\n-      yield* log({\n-        direction: \"incoming\",\n-        stage: \"decoded\",\n-        payload: {\n-          type: \"agent.opened\",\n-          agentId: agent.agentId,\n-        },\n-      });\n-\n       const cwd =\n         typeof input.options.local?.cwd === \"string\"\n           ? input.options.local.cwd\n           : input.options.local?.cwd?.[0];\n+      const storeCwd = input.storeCwd;\n+      const storeWorkspace =\n+        input.operation === \"resume\" && storeCwd !== undefined ? storeCwd : cwd;\n+      const ownedStoreLease =\n+        input.options.local?.store === undefined && storeWorkspace !== undefined\n+          ? yield* acquireWorkspaceStore(storeWorkspace, `agent.${input.operation}`)\n+          : undefined;\n+      let storeReleased = false;\n+      const disposeOwnedStore =\n+        ownedStoreLease === undefined || storeWorkspace === undefined\n+          ? Effect.void\n+          : Effect.suspend(() => {\n+              if (storeReleased) return Effect.void;\n+              storeReleased = true;\n+              return releaseWorkspaceStore(storeWorkspace, ownedStoreLease);\n+            });\n+      const effectiveStore =\n+        ownedStoreLease === undefined ? input.options.local?.store : ownedStoreLease.wrapped;\n+      const effectiveOptions: AgentOptions =\n+        effectiveStore === undefined || effectiveStore === input.options.local?.store\n+          ? input.options\n+          : {\n+              ...input.options,\n+              local: {\n+                ...input.options.local,\n+                store: effectiveStore,\n+              },\n+            };\n+\n+      const { storePlatform, agent } = yield* Effect.gen(function* () {\n+        const resolvedStorePlatform =\n+          input.operation === \"resume\" &&\n+          storeCwd !== undefined &&\n+          storeCwd !== input.options.local?.cwd\n+            ? yield* Effect.tryPromise({\n+                try: () =>\n+                  createAgentPlatform({\n+                    workspaceRef: storeCwd,\n+                    ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),\n+                  }),\n+                catch: (cause) => runnerError(cause, \"agent.resume\"),\n+              })\n+            : undefined;\n+        const openedAgent = yield* Effect.tryPromise({\n+          try: () =>\n+            input.operation === \"create\"\n+              ? Agent.create(effectiveOptions)\n+              : resolvedStorePlatform === undefined\n+                ? Agent.resume(input.agentId!, effectiveOptions)\n+                : resolvedStorePlatform.resumeAgent(input.agentId!, effectiveOptions),\n+          catch: (cause) => runnerError(cause, `agent.${input.operation}`),\n+        });\n+        yield* log({\n+          direction: \"incoming\",\n+          stage: \"decoded\",\n+          payload: {\n+            type: \"agent.opened\",\n+            agentId: openedAgent.agentId,\n+          },\n+        });\n+        return { storePlatform: resolvedStorePlatform, agent: openedAgent };\n+      }).pipe(Effect.onExit((exit) => (Exit.isFailure(exit) ? disposeOwnedStore : Effect.void)));\n+      let shellListener: ((event: CursorBackgroundShellEvent) => void) | undefined;\n+\n       const runOptions = {\n         runtime: \"local\" as const,\n         ...(cwd === undefined ? {} : { cwd }),\n-        ...(input.options.local?.store === undefined ? {} : { store: input.options.local.store }),\n+        ...(effectiveStore === undefined ? {} : { store: effectiveStore }),\n       };\n       let abandonedRunRecoveryAvailable = input.operation === \"resume\";\n       const storeView = async () =>\n         storePlatform ??\n         (await createAgentPlatform({\n           ...(cwd === undefined ? {} : { workspaceRef: cwd }),\n-          ...(input.options.local?.store === undefined\n-            ? {}\n-            : { localStore: input.options.local.store }),\n+          ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),\n         }));\n \n       return {\n@@ -879,9 +1027,7 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n                   ? Agent.messages.list(agent.agentId, {\n                       runtime: \"local\",\n                       ...(cwd === undefined ? {} : { cwd }),\n-                      ...(input.options.local?.store === undefined\n-                        ? {}\n-                        : { store: input.options.local.store }),\n+                      ...(effectiveStore === undefined ? {} : { store: effectiveStore }),\n                     })\n                   : storePlatform.getAgentMessages(agent.agentId),\n               catch: (cause) => runnerError(cause, \"agent.messages.list\"),\n@@ -1010,6 +1156,7 @@ export const makeCursorAgentSdkRunner = Effect.fn(\"makeCursorAgentSdkRunner\")(fu\n               catch: (cause) => runnerError(cause, \"agent.close\"),\n             }),\n           ),\n+          Effect.ensuring(disposeOwnedStore),\n         ),\n       } satisfies CursorAgentSdkSession;\n     }),\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts\nnew file mode 100644\nindex 0000000000..430907b101\n--- /dev/null\n+++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts\n@@ -0,0 +1,742 @@\n+import * as NodeServices from \"@effect/platform-node/NodeServices\";\n+import { assert, describe, it } from \"@effect/vitest\";\n+import { ProviderSessionId, ThreadId } from \"@t3tools/contracts\";\n+import { AgentScope } from \"@t3tools/shared/AgentScope\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n+import * as Deferred from \"effect/Deferred\";\n+import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n+import * as Fiber from \"effect/Fiber\";\n+import * as FileSystem from \"effect/FileSystem\";\n+import * as Path from \"effect/Path\";\n+\n+import * as CursorAgentSdk from \"./CursorAgentSdk.ts\";\n+import * as CursorAgentSdkProcessRunner from \"./CursorAgentSdkProcessRunner.ts\";\n+import {\n+  deserializeRunResult,\n+  deserializeWorkerError,\n+  serializeRunResult,\n+  serializeWorkerError,\n+} from \"./CursorAgentSdkWorkerProtocol.ts\";\n+import { isCursorSdkError, tagCursorSdkError } from \"./sdk.ts\";\n+\n+// Minimal fake worker script implementing the NDJSON worker protocol in a real child Node process.\n+const FAKE_WORKER_SCRIPT = `\n+const readline = require(\"node:readline\");\n+const rawWrite = process.stdout.write.bind(process.stdout);\n+const send = (msg) => rawWrite(JSON.stringify(msg) + \"\\\\n\");\n+const mode = process.env.FAKE_WORKER_MODE || \"ok\";\n+\n+const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });\n+rl.on(\"line\", (line) => {\n+  if (!line.trim()) return;\n+  const req = JSON.parse(line);\n+  if (req.type === \"open\") {\n+    if (mode === \"config-error\") {\n+      send({\n+        type: \"response\",\n+        id: req.id,\n+        ok: false,\n+        error: {\n+          method: \"agent.create\",\n+          cause: {\n+            name: \"ConfigurationError\",\n+            message: \"Cannot use this model: bad-model\",\n+            sdkErrorKind: \"ConfigurationError\",\n+          },\n+        },\n+      });\n+      return;\n+    }\n+    rawWrite(\"non-json noise that must be ignored\\\\n\");\n+    send({ type: \"response\", id: req.id, ok: true, result: { agentId: \"agent-worker-1\" } });\n+    return;\n+  }\n+  if (req.type === \"send\") {\n+    if (mode === \"hang-send\") {\n+      send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.started\", runId: \"pending\", agentId: \"agent-worker-1\" } } });\n+      return;\n+    }\n+    if (mode === \"crash-mid-run\") {\n+      send({ type: \"response\", id: req.id, ok: true, result: { runId: \"run-crash\", agentId: \"agent-worker-1\" } });\n+      process.stderr.write(\"fatal worker boom\\\\n\");\n+      process.exit(17);\n+      return;\n+    }\n+    // Emit an early delta before the send response to verify parent buffering/ordering.\n+    send({ type: \"delta\", sendId: req.id, update: { type: \"text-delta\", text: \"early-\" } });\n+    send({ type: \"response\", id: req.id, ok: true, result: { runId: \"run-worker-1\", agentId: \"agent-worker-1\" } });\n+    if (mode === \"cancel\") {\n+      return;\n+    }\n+    send({ type: \"delta\", sendId: req.id, update: { type: \"text-delta\", text: \"late\" } });\n+    send({\n+      type: \"runDone\",\n+      sendId: req.id,\n+      ok: true,\n+      result: {\n+        id: \"run-worker-1\",\n+        requestId: \"req-1\",\n+        status: \"finished\",\n+        result: \"early-late\",\n+        model: { id: \"default\" },\n+        durationMs: 5,\n+      },\n+    });\n+    if (mode === \"exit-after-done\") {\n+      rawWrite(\"\", () => process.exit(0));\n+    }\n+    if (mode === \"background-shell\" && req.listenBackgroundShells) {\n+      send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"started\", id: \"sh-1\", pid: 4101, command: \"sleep 60\" } });\n+      send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"started\", id: \"sh-2\", pid: 4102, command: \"tail -f\" } });\n+    }\n+    return;\n+  }\n+  if (req.type === \"stopBackgroundShell\") {\n+    send({ type: \"backgroundShell\", sessionId: req.sessionId, event: { type: \"ended\", id: req.shellId, pid: 4101, command: \"sleep 60\", stopped: true, exitCode: undefined, outputPath: undefined } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    if (mode === \"background-shell\") {\n+      rawWrite(\"\", () => process.exit(19));\n+    }\n+    return;\n+  }\n+  if (req.type === \"steer\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: \"complete_delivered\" });\n+    return;\n+  }\n+  if (req.type === \"cancel\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.cancel\", runId: \"run-worker-1\" } } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    send({\n+      type: \"runDone\",\n+      sendId: req.sendId,\n+      ok: true,\n+      result: {\n+        id: \"run-worker-1\",\n+        requestId: \"req-1\",\n+        status: \"cancelled\",\n+        model: { id: \"default\" },\n+        durationMs: 2,\n+      },\n+    });\n+    return;\n+  }\n+  if (req.type === \"listMessages\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: [{ id: \"m1\", role: \"assistant\", text: \"early-late\" }] });\n+    return;\n+  }\n+  if (req.type === \"readContextUsage\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: { usedTokens: 120, maxTokens: 1000 } });\n+    return;\n+  }\n+  if (req.type === \"runCheckpointed\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: req.runId === \"run-worker-1\" });\n+    return;\n+  }\n+  if (req.type === \"rewindAfterRun\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"textGenerate\" && mode === \"hang-text\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.started\", runId: \"text\", agentId: \"text\" } } });\n+    return;\n+  }\n+  if (req.type === \"cancelTextGenerate\") {\n+    send({ type: \"protocolLog\", providerSessionId: \"provider-session-worker-test\", event: { direction: \"incoming\", stage: \"decoded\", payload: { type: \"run.cancel\", runId: \"text\" } } });\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"textGenerate\") {\n+    if (mode === \"rate-limit-text\") {\n+      send({\n+        type: \"response\",\n+        id: req.id,\n+        ok: true,\n+        result: {\n+          id: \"run-tg-1\",\n+          requestId: \"req-tg-1\",\n+          status: \"error\",\n+          model: { id: \"default\" },\n+          durationMs: 3,\n+          error: {\n+            name: \"RateLimitError\",\n+            message: \"Too many requests\",\n+            code: \"PRO_USER_USAGE_LIMIT\",\n+            status: 429,\n+            sdkErrorKind: \"CursorSdkError\",\n+          },\n+        },\n+      });\n+      return;\n+    }\n+    send({\n+      type: \"response\",\n+      id: req.id,\n+      ok: true,\n+      result: {\n+        id: \"run-tg-1\",\n+        requestId: \"req-tg-1\",\n+        status: \"finished\",\n+        result: JSON.stringify({ title: \"Out of process\" }),\n+        model: { id: \"default\" },\n+        durationMs: 3,\n+      },\n+    });\n+    return;\n+  }\n+  if (req.type === \"closeSession\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    return;\n+  }\n+  if (req.type === \"close\") {\n+    send({ type: \"response\", id: req.id, ok: true, result: null });\n+    rawWrite(\"\", () => process.exit(0));\n+  }\n+});\n+rl.on(\"close\", () => process.exit(0));\n+`;\n+\n+const openInput = {\n+  operation: \"create\" as const,\n+  options: { model: { id: \"default\" } },\n+  threadId: ThreadId.make(\"thread-worker-test\"),\n+  providerSessionId: ProviderSessionId.make(\"provider-session-worker-test\"),\n+};\n+\n+describe(\"CursorAgentSdkWorkerProtocol\", () => {\n+  it(\"preserves SDK error classification, rate limits, and abort causes without loading @cursor/sdk\", () => {\n+    const configErr = tagCursorSdkError(\n+      new Error(\"Cannot use this model: mystery\"),\n+      \"ConfigurationError\",\n+    );\n+    const restoredConfig = deserializeWorkerError(serializeWorkerError(configErr));\n+    assert.isTrue(isCursorSdkError(restoredConfig, \"ConfigurationError\"));\n+    assert.isTrue(isCursorSdkError(restoredConfig, \"CursorSdkError\"));\n+    assert.isFalse(isCursorSdkError(restoredConfig, \"AuthenticationError\"));\n+\n+    const rateErr = Object.assign(new Error(\"Quota exceeded\"), {\n+      name: \"RateLimitError\",\n+      code: \"PRO_USER_USAGE_LIMIT\",\n+      status: 429,\n+    });\n+    const restoredResult = deserializeRunResult(\n+      serializeRunResult({\n+        id: \"r1\",\n+        requestId: \"req1\",\n+        status: \"error\",\n+        model: { id: \"default\" },\n+        durationMs: 1,\n+        error: rateErr,\n+      } as never),\n+    );\n+    assert.isTrue(CursorAgentSdk.isCursorUsageLimitError(restoredResult.error));\n+    assert.equal(restoredResult.error?.message, \"Quota exceeded\");\n+\n+    const abortInner = Object.assign(new Error(\"aborted\"), { name: \"AbortError\" });\n+    const wrappedAbort = new Error(\"outer\", { cause: abortInner });\n+    const restoredAbort = deserializeWorkerError(serializeWorkerError(wrappedAbort));\n+    assert.isTrue(CursorAgentSdk.isCursorCancellationError(restoredAbort));\n+\n+    const nullProto = Object.create(null) as Record<string, unknown>;\n+    const restoredNullProto = deserializeWorkerError(serializeWorkerError(nullProto));\n+    assert.equal(restoredNullProto.message, \"[Unserializable error]\");\n+  });\n+});\n+\n+describe(\"CursorAgentSdkProcessRunner\", () => {\n+  const writeFakeWorker = Effect.gen(function* () {\n+    const fs = yield* FileSystem.FileSystem;\n+    const path = yield* Path.Path;\n+    const dir = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-cursor-worker-test-\" });\n+    const scriptPath = path.join(dir, \"fake-worker.cjs\");\n+    yield* fs.writeFileString(scriptPath, FAKE_WORKER_SCRIPT);\n+    return scriptPath;\n+  });\n+\n+  it.live(\n+    \"runs a full session out of process with ordered deltas, scope hooks, and clean shutdown\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const registeredPids: Array<number> = [];\n+          const unregisteredPids: Array<number> = [];\n+          const stoppedUnits: Array<string> = [];\n+          const protocolEvents: Array<string> = [];\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              registerProcess: (pid) => {\n+                registeredPids.push(pid);\n+                return () => unregisteredPids.push(pid);\n+              },\n+            }),\n+            protocolLoggerFor: () => (event) =>\n+              Effect.sync(() => {\n+                protocolEvents.push(event.payload.type);\n+              }),\n+          }).pipe(\n+            Effect.provideService(AgentScope, {\n+              wrap: ({ command, args, name }) =>\n+                Effect.succeed({ command, args, unit: `unit-${name}` }),\n+              oomKilled: () => Effect.succeed(false),\n+              stop: (unit) =>\n+                Effect.sync(() => {\n+                  stoppedUnits.push(unit);\n+                }),\n+              kill: () => Effect.succeed(false),\n+              clear: () => Effect.void,\n+            }),\n+          );\n+\n+          const session = yield* runner.open(openInput);\n+          assert.equal(session.agentId, \"agent-worker-1\");\n+          assert.isTrue(session.isAlive?.());\n+          const otherSession = yield* runner.open({\n+            ...openInput,\n+            threadId: ThreadId.make(\"thread-worker-test-2\"),\n+            providerSessionId: ProviderSessionId.make(\"provider-session-worker-test-2\"),\n+          });\n+          yield* otherSession.close;\n+          assert.isFalse(otherSession.isAlive?.());\n+          assert.isTrue(session.isAlive?.());\n+          assert.lengthOf(registeredPids, 1);\n+          assert.deepEqual(unregisteredPids, []);\n+\n+          const receivedDeltas: Array<string> = [];\n+          const firstDeltaGate = yield* Deferred.make<void>();\n+          const run = yield* session.send({\n+            message: \"hi\",\n+            onDelta: (update) =>\n+              Effect.gen(function* () {\n+                const text = (update as { readonly text?: string }).text ?? \"\";\n+                if (text === \"early-\") {\n+                  yield* Deferred.succeed(firstDeltaGate, undefined);\n+                }\n+                receivedDeltas.push(text);\n+              }),\n+          });\n+          assert.equal(run.runId, \"run-worker-1\");\n+          yield* Deferred.await(firstDeltaGate);\n+\n+          const steerOutcome = yield* run.steer!(\"change course\");\n+          assert.equal(steerOutcome, \"complete_delivered\");\n+\n+          const result = yield* run.wait;\n+          assert.equal(result.status, \"finished\");\n+          assert.equal(result.result, \"early-late\");\n+          assert.deepEqual(receivedDeltas, [\"early-\", \"late\"]);\n+\n+          const [messagesA, messagesB] = yield* Effect.all(\n+            [session.listMessages, session.listMessages],\n+            { concurrency: \"unbounded\" },\n+          );\n+          assert.lengthOf(messagesA, 1);\n+          assert.lengthOf(messagesB, 1);\n+          const usage = yield* session.readContextUsage!;\n+          assert.deepEqual(usage, { usedTokens: 120, maxTokens: 1000 });\n+          assert.isTrue(yield* session.runCheckpointed!(\"run-worker-1\"));\n+          assert.isFalse(yield* session.runCheckpointed!(\"other\"));\n+          yield* session.rewindAfterRun!(\"run-worker-1\");\n+          yield* session.close;\n+          assert.isFalse(session.isAlive?.());\n+\n+          assert.deepEqual(unregisteredPids, registeredPids);\n+          assert.deepEqual(stoppedUnits, [\"unit-cursor-sdk\"]);\n+          assert.include(protocolEvents, \"agent.open\");\n+          assert.include(protocolEvents, \"agent.opened\");\n+          assert.include(protocolEvents, \"run.started\");\n+          assert.include(protocolEvents, \"interaction.update\");\n+          assert.include(protocolEvents, \"run.completed\");\n+          assert.include(protocolEvents, \"agent.close\");\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"preserves ConfigurationError classification across IPC and cleans up on open failure\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          let unregistered = false;\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"config-error\" },\n+              registerProcess: () => () => {\n+                unregistered = true;\n+              },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const error = yield* Effect.flip(runner.open(openInput));\n+          assert.isTrue(isCursorSdkError(error.cause, \"ConfigurationError\"));\n+          assert.isTrue(\n+            error.cause instanceof Error &&\n+              error.cause.message.startsWith(\"Cannot use this model:\"),\n+          );\n+          assert.isTrue(unregistered);\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"fails run.wait with exit code and stderr when the worker crashes mid-run\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const unregistered = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"crash-mid-run\" },\n+            registerProcess: () => () => {\n+              Deferred.doneUnsafe(unregistered, Exit.void);\n+            },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+\n+        const session = yield* runner.open(openInput);\n+        const run = yield* session.send({ message: \"hi\" });\n+        const error = yield* Effect.flip(run.wait);\n+        const msg = CursorAgentSdk.cursorSdkFailureMessage(error);\n+        assert.include(msg, \"code 17\");\n+        assert.notInclude(msg, \"fatal worker boom\");\n+        const diagnostic = error.cause instanceof Error ? error.cause.cause : undefined;\n+        assert.isTrue(\n+          diagnostic instanceof Error && diagnostic.message.includes(\"fatal worker boom\"),\n+        );\n+        // Dead worker scope tears down immediately instead of waiting for sessions to close.\n+        yield* Deferred.await(unregistered);\n+        assert.isFalse(session.isAlive?.());\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"preserves an already-received runDone when the worker exits while onDelta is running\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const workerTerminated = yield* Deferred.make<void>();\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"exit-after-done\" },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+            onWorkerTerminated: () => {\n+              Deferred.doneUnsafe(workerTerminated, Exit.void);\n+            },\n+          });\n+\n+          const session = yield* runner.open(openInput);\n+          const deltaStarted = yield* Deferred.make<void>();\n+          const releaseDelta = yield* Deferred.make<void>();\n+          const run = yield* session.send({\n+            message: \"hi\",\n+            onDelta: (update) =>\n+              Effect.gen(function* () {\n+                if ((update as { readonly text?: string }).text === \"early-\") {\n+                  yield* Deferred.succeed(deltaStarted, undefined);\n+                  yield* Deferred.await(releaseDelta);\n+                }\n+              }),\n+          });\n+          yield* Deferred.await(deltaStarted);\n+          yield* Deferred.await(workerTerminated);\n+          yield* Deferred.succeed(releaseDelta, undefined);\n+          const result = yield* run.wait;\n+          assert.equal(result.status, \"finished\");\n+          assert.equal(result.result, \"early-late\");\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"cancels a started run when send is interrupted before handing it off\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const startedLogged = yield* Deferred.make<void>();\n+        const cancelled = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"cancel\" },\n+          }),\n+          protocolLoggerFor: () => (event) => {\n+            if (event.payload.type === \"run.started\") {\n+              return Deferred.succeed(startedLogged, undefined).pipe(Effect.andThen(Effect.never));\n+            }\n+            if (event.payload.type === \"run.cancel\" && event.direction === \"incoming\") {\n+              return Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid);\n+            }\n+            return Effect.void;\n+          },\n+        });\n+        const session = yield* runner.open(openInput);\n+        const sending = yield* Effect.forkChild(session.send({ message: \"hi\" }));\n+        yield* Deferred.await(startedLogged);\n+        yield* Fiber.interrupt(sending);\n+        yield* Deferred.await(cancelled);\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"closes the session when send is interrupted after transmission before acknowledgment\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const receivedByWorker = yield* Deferred.make<void>();\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"hang-send\" },\n+            }),\n+            protocolLoggerFor: () => (event) =>\n+              event.payload.type === \"run.started\"\n+                ? Deferred.succeed(receivedByWorker, undefined).pipe(Effect.asVoid)\n+                : Effect.void,\n+          });\n+\n+          const session = yield* runner.open(openInput);\n+          assert.isTrue(session.isAlive?.());\n+          const sending = yield* Effect.forkChild(session.send({ message: \"hi\" }));\n+          yield* Deferred.await(receivedByWorker);\n+          yield* Fiber.interrupt(sending);\n+          assert.isFalse(session.isAlive?.());\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"cancels an interrupted text generation in a worker that other sessions keep alive\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+        const received = yield* Deferred.make<void>();\n+        const cancelled = yield* Deferred.make<void>();\n+\n+        const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"hang-text\" },\n+          }),\n+          protocolLoggerFor: () => (event) =>\n+            event.payload.type === \"run.started\"\n+              ? Deferred.succeed(received, undefined).pipe(Effect.asVoid)\n+              : event.payload.type === \"run.cancel\"\n+                ? Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid)\n+                : Effect.void,\n+        });\n+        const session = yield* runner.open(openInput);\n+        const generating = yield* Effect.forkChild(\n+          runner.textGenerate!({\n+            prompt: \"title\",\n+            apiKey: \"key\",\n+            model: { id: \"default\" },\n+            cwd: \"/tmp\",\n+            stateRoot: \"/tmp\",\n+          }),\n+        );\n+        yield* Deferred.await(received);\n+        yield* Fiber.interrupt(generating);\n+        yield* Deferred.await(cancelled);\n+        assert.isTrue(session.isAlive?.());\n+        yield* session.close;\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\"forwards cancel and runs textGenerate in a disposable child process\", () =>\n+    Effect.scoped(\n+      Effect.gen(function* () {\n+        const scriptPath = yield* writeFakeWorker;\n+        const executable = yield* HostProcess.ExecutablePath;\n+\n+        const cancelRunner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"cancel\" },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+        const session = yield* cancelRunner.open(openInput);\n+        const run = yield* session.send({ message: \"hi\" });\n+        yield* run.cancel;\n+        const cancelled = yield* run.wait;\n+        assert.equal(cancelled.status, \"cancelled\");\n+        yield* session.close;\n+\n+        let textGenUnregistered = false;\n+        const textGenRunner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+          resolveLaunch: Effect.succeed({\n+            command: executable,\n+            args: [scriptPath],\n+            env: { FAKE_WORKER_MODE: \"rate-limit-text\" },\n+            registerProcess: () => () => {\n+              textGenUnregistered = true;\n+            },\n+          }),\n+          protocolLoggerFor: () => undefined,\n+        });\n+        const textResult = yield* textGenRunner.textGenerate!({\n+          prompt: \"title\",\n+          apiKey: \"key\",\n+          model: { id: \"default\" },\n+          cwd: \"/tmp\",\n+          stateRoot: \"/tmp\",\n+        });\n+        assert.equal(textResult.status, \"error\");\n+        assert.isTrue(CursorAgentSdk.isCursorUsageLimitError(textResult.error));\n+        assert.isTrue(textGenUnregistered);\n+      }),\n+    ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"settles active runs on a closed session without disrupting peer sessions on the shared worker\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+          const registeredPids: Array<number> = [];\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"cancel\" },\n+              registerProcess: (pid) => {\n+                registeredPids.push(pid);\n+                return () => {};\n+              },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const sessionA = yield* runner.open(openInput);\n+          const sessionB = yield* runner.open({\n+            ...openInput,\n+            threadId: ThreadId.make(\"thread-worker-test-peer\"),\n+            providerSessionId: ProviderSessionId.make(\"provider-session-worker-test-peer\"),\n+          });\n+          assert.lengthOf(registeredPids, 1);\n+\n+          // Start a run on sessionA that stays pending, then close sessionA while sessionB keeps the worker alive.\n+          const runA = yield* sessionA.send({ message: \"hi\" });\n+          const waitA = yield* Effect.forkChild(Effect.flip(runA.wait));\n+          yield* sessionA.close;\n+          const errorA = yield* Fiber.join(waitA);\n+          assert.include(CursorAgentSdk.cursorSdkFailureMessage(errorA), \"closed\");\n+          assert.isFalse(sessionA.isAlive?.());\n+          assert.isTrue(sessionB.isAlive?.());\n+          assert.lengthOf(yield* sessionB.listMessages, 1);\n+          yield* sessionB.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+\n+  it.live(\n+    \"forwards background shell events across IPC, routes stop(), and ends orphans on worker crash\",\n+    () =>\n+      Effect.scoped(\n+        Effect.gen(function* () {\n+          const scriptPath = yield* writeFakeWorker;\n+          const executable = yield* HostProcess.ExecutablePath;\n+\n+          const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({\n+            resolveLaunch: Effect.succeed({\n+              command: executable,\n+              args: [scriptPath],\n+              env: { FAKE_WORKER_MODE: \"background-shell\" },\n+            }),\n+            protocolLoggerFor: () => undefined,\n+          });\n+\n+          const events: Array<object> = [];\n+          const startedFirst = yield* Deferred.make<() => void>();\n+          const bothEnded = yield* Deferred.make<void>();\n+          let endedCount = 0;\n+\n+          const session = yield* runner.open(openInput);\n+          const run = yield* session.send({\n+            message: \"watch it\",\n+            onBackgroundShell: (event) =>\n+              Effect.gen(function* () {\n+                if (event.type === \"started\") {\n+                  const { stop, ...started } = event;\n+                  events.push(started);\n+                  if (event.id === \"sh-1\") yield* Deferred.succeed(startedFirst, stop);\n+                  return;\n+                }\n+                events.push(event);\n+                endedCount += 1;\n+                if (endedCount === 2) yield* Deferred.succeed(bothEnded, undefined);\n+              }),\n+          });\n+          yield* run.wait;\n+\n+          // Stopping sh-1 triggers a worker-side ended event, then the fake worker crashes to\n+          // verify sh-2 gets a synthesized ended(stopped: true) event.\n+          const stopFirst = yield* Deferred.await(startedFirst);\n+          stopFirst();\n+          yield* Deferred.await(bothEnded);\n+\n+          assert.deepEqual(events, [\n+            { type: \"started\", id: \"sh-1\", pid: 4101, command: \"sleep 60\" },\n+            { type: \"started\", id: \"sh-2\", pid: 4102, command: \"tail -f\" },\n+            {\n+              type: \"ended\",\n+              id: \"sh-1\",\n+              pid: 4101,\n+              command: \"sleep 60\",\n+              stopped: true,\n+              exitCode: undefined,\n+              outputPath: undefined,\n+            },\n+            {\n+              type: \"ended\",\n+              id: \"sh-2\",\n+              pid: 4102,\n+              command: \"tail -f\",\n+              stopped: true,\n+              exitCode: undefined,\n+              outputPath: undefined,\n+            },\n+          ]);\n+          yield* session.close;\n+        }),\n+      ).pipe(Effect.provide(NodeServices.layer)),\n+  );\n+});\ndiff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts\nnew file mode 100644\nindex 0000000000..ed97c62288\n--- /dev/null\n+++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts\n@@ -0,0 +1,1167 @@\n+import type { AgentMessage, InteractionUpdate, RunResult, SteerAckOutcome } from \"@cursor/sdk\";\n+import * as ProviderEventLoggers from \"@t3tools/provider-core/server/ProviderEventLoggers\";\n+import { AgentScope } from \"@t3tools/shared/AgentScope\";\n+import * as HostProcess from \"@t3tools/shared/HostProcess\";\n+import * as Cause from \"effect/Cause\";\n+import * as Deferred from \"effect/Deferred\";\n+import * as Duration from \"effect/Duration\";\n+import * as Effect from \"effect/Effect\";\n+import * as Exit from \"effect/Exit\";\n+import * as Fiber from \"effect/Fiber\";\n+import * as Layer from \"effect/Layer\";\n+import * as Option from \"effect/Option\";\n+import * as ChildProcess from \"effect/process/ChildProcess\";\n+import * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\n+import * as Queue from \"effect/Queue\";\n+import * as Ref from \"effect/Ref\";\n+import * as Scope from \"effect/Scope\";\n+import * as Semaphore from \"effect/Semaphore\";\n+import * as Stream from \"effect/Stream\";\n+\n+import * as CursorAgentSdk from \"./CursorAgentSdk.ts\";\n+import {\n+  type CursorWorkerMessage,\n+  type CursorWorkerRequest,\n+  type CursorWorkerResponsePayload,\n+  type SerializedRunResult,\n+  type SerializedRunnerFailure,\n+  decodeWorkerFrame,\n+  deserializeRunResult,\n+  deserializeWorkerError,\n+  encodeWorkerFrame,\n+} from \"./CursorAgentSdkWorkerProtocol.ts\";\n+\n+const WORKER_CLOSE_TIMEOUT = Duration.seconds(3);\n+const WORKER_EXIT_TIMEOUT = Duration.seconds(2);\n+const MAX_STDERR_CHARS = 8_192;\n+\n+export interface CursorSdkWorkerLaunch {\n+  readonly command: string;\n+  readonly args: ReadonlyArray<string>;\n+  readonly env?: NodeJS.ProcessEnv | undefined;\n+  readonly registerProcess?: ((pid: number) => () => void) | undefined;\n+}\n+\n+type RunQueueItem =\n+  | { readonly _tag: \"delta\"; readonly update: InteractionUpdate }\n+  | { readonly _tag: \"done\"; readonly ok: true; readonly result: RunResult }\n+  | {\n+      readonly _tag: \"done\";\n+      readonly ok: false;\n+      readonly error: CursorAgentSdk.CursorAgentSdkRunnerError;\n+    };\n+\n+interface ActiveWorkerRun {\n+  readonly sessionId: number;\n+  readonly queue: Queue.Queue<RunQueueItem>;\n+  readonly waitDeferred: Deferred.Deferred<RunResult, CursorAgentSdk.CursorAgentSdkRunnerError>;\n+  doneEnqueued: boolean;\n+}\n+\n+function toRunnerError(method: string, cause: unknown): CursorAgentSdk.CursorAgentSdkRunnerError {\n+  return CursorAgentSdk.isCursorAgentSdkRunnerError(cause)\n+    ? cause\n+    : new CursorAgentSdk.CursorAgentSdkRunnerError({ method, cause });\n+}\n+\n+function fromSerializedFailure(\n+  failure: SerializedRunnerFailure,\n+): CursorAgentSdk.CursorAgentSdkRunnerError {\n+  return new CursorAgentSdk.CursorAgentSdkRunnerError({\n+    method: failure.method,\n+    cause: deserializeWorkerError(failure.cause),\n+  });\n+}\n+\n+function workerExitError(method: string, exitCode: number | undefined, stderr: string) {\n+  const trimmedStderr = stderr.trim();\n+  const detail = `Cursor SDK worker exited unexpectedly${exitCode === undefined ? \"\" : ` (code ${exi",
      "stagedSummary": " apps/server/package.json                           |    2 +-\n apps/server/src/binMain.ts                         |    6 +\n ...viderOrchestrationAdapterInfrastructure.test.ts |   37 +\n .../ProviderOrchestrationAdapterInfrastructure.ts  |   36 +-\n packages/provider-cursor/package.json              |   10 +-\n .../src/server/CursorAgentSdk.test.ts              |  104 +-\n .../provider-cursor/src/server/CursorAgentSdk.ts   |  235 +++-\n .../src/server/CursorAgentSdkProcessRunner.test.ts |  742 +++++++++++++\n .../src/server/CursorAgentSdkProcessRunner.ts      | 1167 ++++++++++++++++++++\n .../src/server/CursorAgentSdkWorker.ts             |  647 +++++++++++\n .../src/server/CursorAgentSdkWorkerProtocol.ts     |  304 +++++\n .../provider-cursor/src/server/adapter.test.ts     |  137 +++\n packages/provider-cursor/src/server/adapter.ts     |    3 +-\n packages/provider-cursor/src/server/driver.ts      |    1 +\n packages/provider-cursor/src/server/sdk.ts         |   42 +-\n .../src/server/textGeneration.test.ts              |   37 +\n .../provider-cursor/src/server/textGeneration.ts   |  279 +++--\n ...r__sdk@1.4.1.patch => @cursor__sdk@1.4.2.patch} |  101 +-\n pnpm-lock.yaml                                     |   58 +-\n pnpm-workspace.yaml                                |    4 +-\n 20 files changed, 3727 insertions(+), 225 deletions(-)\n"
    }
  }
]