tsugite-cursor 0.27.0__py3-none-any.whl
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,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)
|
|
@@ -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,6 @@
|
|
|
1
|
+
tsugite_cursor/__init__.py,sha256=RYYFgRjIopFS5ht7WCphXS0FhAzEqQ61AydfZQEovVo,206
|
|
2
|
+
tsugite_cursor/provider.py,sha256=-FKZb_mBWJOVcCeLKymRjy3Rk1jI2M6LsNhB8tplEe0,13101
|
|
3
|
+
tsugite_cursor-0.27.0.dist-info/METADATA,sha256=2L8FpR3eiWJ9JbWc8oeXe6wyj8fK5V1_J1MidBiKWCI,265
|
|
4
|
+
tsugite_cursor-0.27.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
5
|
+
tsugite_cursor-0.27.0.dist-info/entry_points.txt,sha256=oX-tsCEfBUWg2BvlDdBCJG6fr52XAW6JTAfQ17sjZ6I,60
|
|
6
|
+
tsugite_cursor-0.27.0.dist-info/RECORD,,
|