tsugite-cursor 0.27.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ # ---> Python
2
+ # Byte-compiled / optimized / DLL files
3
+ __pycache__/
4
+ *.py[cod]
5
+ *$py.class
6
+
7
+ # C extensions
8
+ *.so
9
+
10
+ # Distribution / packaging
11
+ .Python
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ /lib/
19
+ /lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ wheels/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ #Pipfile.lock
97
+
98
+ # poetry
99
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
103
+ #poetry.lock
104
+
105
+ # pdm
106
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
107
+ #pdm.lock
108
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
109
+ # in version control.
110
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
111
+ .pdm.toml
112
+ .pdm-python
113
+ .pdm-build/
114
+
115
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
116
+ __pypackages__/
117
+
118
+ # Celery stuff
119
+ celerybeat-schedule
120
+ celerybeat.pid
121
+
122
+ # SageMath parsed files
123
+ *.sage.py
124
+
125
+ # Environments
126
+ .env
127
+ .venv
128
+ env/
129
+ venv/
130
+ ENV/
131
+ env.bak/
132
+ venv.bak/
133
+
134
+ # Spyder project settings
135
+ .spyderproject
136
+ .spyproject
137
+
138
+ # Rope project settings
139
+ .ropeproject
140
+
141
+ # mkdocs documentation
142
+ /site
143
+
144
+ # mypy
145
+ .mypy_cache/
146
+ .dmypy.json
147
+ dmypy.json
148
+
149
+ # Pyre type checker
150
+ .pyre/
151
+
152
+ # pytype static type analyzer
153
+ .pytype/
154
+
155
+ # Cython debug symbols
156
+ cython_debug/
157
+
158
+ # PyCharm
159
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
160
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
161
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
162
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
163
+ #.idea/
164
+
165
+ .env
166
+ .env
167
+ benchmark_results/
168
+ test_output/
169
+ .claude/settings.local.json
170
+ std*.txt
171
+ secrets/*
172
+
173
+
174
+ # TODO: temp - I need to clean up the docs
175
+ docs-old/
176
+ docs/design/
177
+ examples/*
178
+ !examples/tsugite-example-plugin/
179
+ /agents/
180
+ .claude/
181
+ .tsugite/
182
+ benchmarks/
183
+ docker-compose.test.yml
184
+ #### TODO ^^^
185
+
186
+ # Vite dep-optimizer cache. Normally under node_modules/.vite, but lands at the
187
+ # cwd's `.vite/` when vite/vitest is run from the repo root, so ignore it anywhere.
188
+ .vite/
189
+ # Built web UI - generated by `mise run web-build`; the wheel bundles it via
190
+ # hatch `artifacts`, git never carries it.
191
+ plugins/tsugite-daemon/tsugite_daemon/web/
192
+ # Re-include frontend source that generic lib/ rules (incl. contributors' global
193
+ # gitignores with Python-style `lib/`) would otherwise silently exclude.
194
+ !plugins/tsugite-daemon/frontend/src/lib/
195
+ !plugins/tsugite-daemon/frontend/src/lib/**
196
+ # Per-job git worktrees provisioned by the daemon.
197
+ .tsugite-jobs/
198
+ /packaging/runtime/.cache/
199
+ # Corporate CA certs dropped in for docker build.
200
+ /docker/ca-certificates/*
201
+ !/docker/ca-certificates/.gitkeep
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.5
2
+ Name: tsugite-cursor
3
+ Version: 0.27.0
4
+ Summary: Tsugite plugin: Cursor provider (routes LLM calls through the Cursor Python SDK)
5
+ Author: Justyn Shull
6
+ Requires-Python: >=3.11
7
+ Requires-Dist: cursor-sdk<2,>=1.3.1
8
+ Requires-Dist: tsugite-cli==0.27.0
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "tsugite-cursor"
3
+ version = "0.27.0"
4
+ description = "Tsugite plugin: Cursor provider (routes LLM calls through the Cursor Python SDK)"
5
+ authors = [{ name = "Justyn Shull" }]
6
+ requires-python = ">=3.11"
7
+ dependencies = [
8
+ "cursor-sdk>=1.3.1,<2",
9
+ "tsugite-cli==0.27.0",
10
+ ]
11
+
12
+ [project.entry-points."tsugite.providers"]
13
+ cursor = "tsugite_cursor:create_provider"
14
+
15
+ [build-system]
16
+ requires = ["hatchling"]
17
+ build-backend = "hatchling.build"
18
+
19
+ [tool.hatch.build.targets.wheel]
20
+ packages = ["tsugite_cursor"]
21
+
22
+ [tool.hatch.build.targets.sdist]
23
+ include = [
24
+ "/tsugite_cursor",
25
+ "/pyproject.toml",
26
+ ]
27
+
28
+ [tool.uv.sources]
29
+ tsugite-cli = { workspace = true }
@@ -0,0 +1,5 @@
1
+ """Tsugite plugin: Cursor provider (routes LLM calls through the Cursor Python SDK)."""
2
+
3
+ from tsugite_cursor.provider import CursorProvider, create_provider
4
+
5
+ __all__ = ["CursorProvider", "create_provider"]
@@ -0,0 +1,304 @@
1
+ """Cursor provider: Cursor models through the Cursor Python SDK (`cursor-sdk`), with Cursor's built-in tools disabled."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import logging
7
+ import re
8
+ from pathlib import Path
9
+ from typing import Any, AsyncIterator
10
+
11
+ from tsugite.config import get_xdg_data_path
12
+ from tsugite.exceptions import AgentExecutionError
13
+ from tsugite.providers.base import (
14
+ CompletionResponse,
15
+ ModelInfo,
16
+ StreamChunk,
17
+ Usage,
18
+ api_key_secret_name,
19
+ default_count_tokens,
20
+ resolve_api_key,
21
+ )
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # The SDK's model catalog has no context window. A `context=` model parameter overrides this default.
26
+ _DEFAULT_CONTEXT_TOKENS = 200_000
27
+ _CONTEXT_PARAM = re.compile(r"^(\d+)([km])$", re.IGNORECASE)
28
+ _MODEL = re.compile(r"^(?P<id>[^\[\]]+?)(?:\[(?P<params>[^\]]*)\])?$")
29
+
30
+
31
+ def parse_model(model: str) -> dict:
32
+ """`composer-2.5` or `claude-opus-4-8[context=1m,effort=high]` into an SDK ModelSelection."""
33
+ match = _MODEL.match(model.strip())
34
+ if not match:
35
+ raise ValueError(f"Invalid Cursor model {model!r}")
36
+ model_id = "default" if match["id"] == "auto" else match["id"]
37
+ params = []
38
+ for item in filter(None, (p.strip() for p in (match["params"] or "").split(","))):
39
+ key, sep, value = item.partition("=")
40
+ if not sep:
41
+ raise ValueError(f"Invalid Cursor model parameter {item!r} in {model!r}, expected key=value")
42
+ params.append({"id": key.strip(), "value": value.strip()})
43
+ return {"id": model_id, **({"params": params} if params else {})}
44
+
45
+
46
+ def session_cwd() -> Path:
47
+ """Empty directory every Cursor agent runs in. The SDK scopes resumable agents to their cwd."""
48
+ path = get_xdg_data_path("cursor/cwd")
49
+ path.mkdir(parents=True, exist_ok=True)
50
+ return path
51
+
52
+
53
+ def _sdk():
54
+ import cursor_sdk
55
+
56
+ return cursor_sdk
57
+
58
+
59
+ def _api_key() -> str:
60
+ if key := resolve_api_key(CursorProvider.api_key_env):
61
+ return key
62
+ raise AgentExecutionError(
63
+ f"No Cursor API key found. Create one in the Cursor dashboard and set {CursorProvider.api_key_env} "
64
+ f"or the {api_key_secret_name(CursorProvider.api_key_env)} secret."
65
+ )
66
+
67
+
68
+ @contextlib.contextmanager
69
+ def _cursor_errors():
70
+ sdk = _sdk()
71
+ try:
72
+ yield
73
+ except sdk.AuthenticationError as e:
74
+ raise AgentExecutionError(f"Cursor rejected the API key: {e}") from e
75
+ except sdk.CursorSDKError as e:
76
+ raise AgentExecutionError(f"Cursor error: {e}") from e
77
+
78
+
79
+ def _text(content: Any) -> str:
80
+ if isinstance(content, list):
81
+ return "\n".join(
82
+ b if isinstance(b, str) else b.get("text", "")
83
+ for b in content
84
+ if isinstance(b, str) or b.get("type") == "text"
85
+ )
86
+ return content or ""
87
+
88
+
89
+ class CursorProvider:
90
+ """One SDK bridge process, and so one Cursor agent, per instance."""
91
+
92
+ api_key_env = "CURSOR_API_KEY"
93
+ cacheable = False
94
+ models_are_definitive = False # the catalog depends on the account
95
+
96
+ def __init__(self, name: str = "cursor"):
97
+ self.name = name
98
+ self._client = None
99
+ self._agent = None
100
+ self._context_window: int | None = None
101
+ self._attachments: list = []
102
+ self._skills: list = []
103
+ self._previous_messages: list = []
104
+ self._resume_session: str | None = None
105
+ self._resume_after_compaction = False
106
+
107
+ def set_context(self, **kwargs: Any) -> None:
108
+ self._attachments = kwargs.get("attachments", [])
109
+ self._skills = kwargs.get("skills", [])
110
+ self._previous_messages = kwargs.get("previous_messages", [])
111
+ self._resume_session = kwargs.get("resume_session")
112
+ self._resume_after_compaction = kwargs.get("resume_after_compaction", False)
113
+
114
+ def get_state(self) -> dict:
115
+ return {"session_id": self._agent.agent_id if self._agent else None, "context_window": self._context_window}
116
+
117
+ async def acompletion(
118
+ self,
119
+ messages: list[dict],
120
+ model: str,
121
+ stream: bool = False,
122
+ **kwargs: Any,
123
+ ) -> CompletionResponse | AsyncIterator[StreamChunk]:
124
+ if self._agent is None:
125
+ system_prompt = ""
126
+ if messages[0].get("role") == "system":
127
+ system_prompt = _text(messages[0]["content"])
128
+ messages = messages[1:]
129
+ self._context_window = self.get_model_info(model).max_input_tokens
130
+ await self._open(model)
131
+ text = self._build_first_message(messages, system_prompt)
132
+ else:
133
+ text = _text(messages[-1]["content"])
134
+
135
+ chunks = self._stream(text)
136
+ return chunks if stream else await self._collect(chunks)
137
+
138
+ async def _open(self, model: str) -> None:
139
+ sdk = _sdk()
140
+ key = _api_key()
141
+ cwd = str(session_cwd())
142
+ with _cursor_errors():
143
+ client = await sdk.AsyncCursorClient.launch_bridge(workspace=cwd)
144
+ try:
145
+ options = {
146
+ "api_key": key,
147
+ "name": "tsugite",
148
+ "model": await self._with_default_params(client, key, parse_model(model)),
149
+ "tools": [],
150
+ "local": {"cwd": cwd, "setting_sources": []},
151
+ }
152
+ if self._resume_session:
153
+ try:
154
+ self._agent = await sdk.AsyncAgent.resume(self._resume_session, options, client=client)
155
+ except sdk.AgentNotFoundError as e:
156
+ logger.warning(
157
+ "Cursor agent %s cannot be resumed (%s), starting a new one with the conversation history",
158
+ self._resume_session,
159
+ e,
160
+ )
161
+ self._resume_session = None
162
+ if self._agent is None:
163
+ self._agent = await sdk.AsyncAgent.create(options, client=client)
164
+ except BaseException:
165
+ await client.aclose()
166
+ raise
167
+ self._client = client
168
+
169
+ @staticmethod
170
+ async def _with_default_params(client, key: str, model: dict) -> dict:
171
+ """Fill in the catalog's default variant params. Some plans refuse a bare id ("Model unavailable on Plus ... with fixed settings")."""
172
+ if "params" in model or model["id"] == "default":
173
+ return model
174
+ catalog = await _sdk().AsyncCursor.models.list(client=client, api_key=key)
175
+ entry = next((m for m in catalog if m.id == model["id"]), None)
176
+ variant = next((v for v in entry.variants if v.is_default), None) if entry else None
177
+ if variant is None:
178
+ return model
179
+ return {"id": entry.id, "params": [{"id": p.id, "value": p.value} for p in variant.params]}
180
+
181
+ async def _collect(self, chunks: AsyncIterator[StreamChunk]) -> CompletionResponse:
182
+ content, reasoning, usage = [], [], None
183
+ async for chunk in chunks:
184
+ content.append(chunk.content)
185
+ reasoning.append(chunk.reasoning_content)
186
+ if chunk.done:
187
+ usage = chunk.usage
188
+ return CompletionResponse(content="".join(content), reasoning_content="".join(reasoning) or None, usage=usage)
189
+
190
+ async def _stream(self, text: str) -> AsyncIterator[StreamChunk]:
191
+ sdk = _sdk()
192
+ with _cursor_errors():
193
+ # run.events() yields interaction updates only while an on_delta callback is registered.
194
+ run = await self._agent.send(text, sdk.SendOptions(on_delta=lambda update: None))
195
+ result = None
196
+ try:
197
+ async for event in run.events():
198
+ update = event.interaction_update
199
+ if isinstance(update, sdk.TextDeltaUpdate):
200
+ yield StreamChunk(content=update.text)
201
+ elif isinstance(update, sdk.ThinkingDeltaUpdate):
202
+ yield StreamChunk(reasoning_content=update.text)
203
+ elif isinstance(update, (sdk.ToolCallStartedUpdate, sdk.PartialToolCallUpdate)):
204
+ raise AgentExecutionError(
205
+ f"Cursor started a tool call ({update.tool_call.get('type', 'unknown')}) although tools are disabled."
206
+ )
207
+ result = await run.wait()
208
+ finally:
209
+ if result is None and run.status not in ("finished", "error", "cancelled", "expired"):
210
+ try:
211
+ await run.cancel()
212
+ except sdk.CursorSDKError as e:
213
+ logger.warning("Cursor run cancel failed: %s", e)
214
+ if result.status != "finished":
215
+ raise AgentExecutionError(f"Cursor run {result.status}: {result.error_message or 'no details'}")
216
+ usage = result.usage
217
+ if usage is not None:
218
+ # input_tokens includes cache reads.
219
+ usage = Usage(
220
+ prompt_tokens=usage.input_tokens,
221
+ completion_tokens=usage.output_tokens,
222
+ total_tokens=usage.input_tokens + usage.output_tokens,
223
+ cached_tokens=usage.cache_read_tokens,
224
+ reasoning_tokens=usage.reasoning_tokens,
225
+ )
226
+ yield StreamChunk(done=True, usage=usage)
227
+
228
+ def _build_first_message(self, messages: list[dict], system_prompt: str) -> str:
229
+ """Latest user message, preceded by the system prompt, context, history and delivery cards the agent has not seen."""
230
+ from tsugite.context_block import build_context_el
231
+ from tsugite.prompt_xml import El, Raw
232
+
233
+ parts = []
234
+ if not self._resume_session or self._resume_after_compaction:
235
+ if context := build_context_el(self._attachments, self._skills, skill_char_limit=4000):
236
+ parts.append(context.render() + "\n")
237
+ if self._previous_messages and not self._resume_session:
238
+ kept = self._trim_history(self._previous_messages, self._context_window // 2)
239
+ dropped = len(self._previous_messages) - len(kept)
240
+ lines = [f"{m.get('role', 'unknown').capitalize()}: {m.get('content', '')}" for m in kept]
241
+ note = f"{dropped} older messages omitted for context" if dropped else None
242
+ history = El("conversation_history", [Raw("\n\n".join(lines))], attrs={"note": note})
243
+ parts.append(history.render() + "\n")
244
+ if self._resume_session:
245
+ parts.extend(self._unseen_delivery_cards())
246
+ for message in reversed(messages):
247
+ if message.get("role") == "user":
248
+ parts.append(_text(message["content"]))
249
+ break
250
+ text = "\n".join(parts)
251
+ if system_prompt and not self._resume_session:
252
+ text = El("tsugite_system_prompt", [Raw(system_prompt)]).render() + "\n\n" + text
253
+ return text
254
+
255
+ @staticmethod
256
+ def _trim_history(history: list[dict], budget: int) -> list[dict]:
257
+ kept, used = [], 0
258
+ for message in reversed(history):
259
+ content = message.get("content", "")
260
+ estimate = len(content) // 4 if isinstance(content, str) else 100
261
+ if used + estimate > budget and kept:
262
+ break
263
+ kept.append(message)
264
+ used += estimate
265
+ return kept[::-1]
266
+
267
+ def _unseen_delivery_cards(self) -> list[str]:
268
+ """Delivery cards other than needs_ack recorded after the last assistant reply. The resumed agent has not seen them."""
269
+ last_reply = max((i for i, m in enumerate(self._previous_messages) if m.get("role") == "assistant"), default=-1)
270
+ cards = []
271
+ for message in self._previous_messages[last_reply + 1 :]:
272
+ content = message.get("content")
273
+ if isinstance(content, str) and content.startswith("<tsugite_delivery "):
274
+ if 'kind="needs_ack"' not in content.split("\n", 1)[0]:
275
+ cards.append(content + "\n")
276
+ return cards
277
+
278
+ async def stop(self) -> None:
279
+ if self._client:
280
+ await self._client.aclose()
281
+ self._client = None
282
+ self._agent = None
283
+
284
+ def count_tokens(self, text: str, model: str) -> int:
285
+ return default_count_tokens(text, model)
286
+
287
+ def get_model_info(self, model: str) -> ModelInfo:
288
+ context = next((p["value"] for p in parse_model(model).get("params", []) if p["id"] == "context"), "")
289
+ match = _CONTEXT_PARAM.match(context)
290
+ if not match:
291
+ return ModelInfo(max_input_tokens=_DEFAULT_CONTEXT_TOKENS)
292
+ scale = 1_000_000 if match[2].lower() == "m" else 1_000
293
+ return ModelInfo(max_input_tokens=int(match[1]) * scale)
294
+
295
+ async def list_models(self) -> list[str]:
296
+ sdk = _sdk()
297
+ key = _api_key()
298
+ with _cursor_errors():
299
+ async with await sdk.AsyncCursorClient.launch_bridge(workspace=str(session_cwd())) as client:
300
+ return [m.id for m in await sdk.AsyncCursor.models.list(client=client, api_key=key)]
301
+
302
+
303
+ def create_provider(name: str = "cursor", **kwargs: Any) -> CursorProvider:
304
+ return CursorProvider(name=name)