@tduyng/pi-cursor 0.0.0-stage → 0.0.2
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.
- package/LICENSE +178 -0
- package/README.md +104 -2
- package/package.json +42 -4
- package/src/catalog.ts +69 -0
- package/src/index.ts +195 -0
- package/src/json.ts +74 -0
- package/src/models.ts +198 -0
- package/src/resume.ts +81 -0
- package/src/sdk.ts +14 -0
- package/src/session.ts +461 -0
- package/src/state.ts +43 -0
- package/src/transcript.ts +210 -0
- package/src/turn.ts +389 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
Use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 tduyng
|
package/README.md
CHANGED
|
@@ -1,3 +1,105 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-cursor
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Cursor models in Pi through the official Cursor SDK. Pi keeps its own system prompt, tools, approvals, compaction and session tree. Cursor is only the authenticated model transport.
|
|
4
|
+
|
|
5
|
+
No Cursor CLI is installed or called. Login is the SDK browser flow, which mints a stored Cursor API key under `~/.cursor/sdk/auth.json`.
|
|
6
|
+
|
|
7
|
+
The provider id is `cursor`, and model ids are Cursor's own ids. `/model cursor/gpt-5.5` and `/model cursor/claude-opus-4-8` work as written.
|
|
8
|
+
|
|
9
|
+
## Requirements
|
|
10
|
+
|
|
11
|
+
- Pi 1.4 or newer.
|
|
12
|
+
- Node 24 or newer.
|
|
13
|
+
- A Cursor account.
|
|
14
|
+
- The extension dependency `@cursor/sdk` 1.0.40, installed by the workspace.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
pi install /path/to/extensions/pi-cursor
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
In this repository the workspace already registers the extension in the root `package.json`.
|
|
23
|
+
|
|
24
|
+
## Login
|
|
25
|
+
|
|
26
|
+
```text
|
|
27
|
+
/cursor login
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The SDK opens the Cursor login page and mints a key when the browser flow finishes. If the browser does not open, the command prints the URL. `/cursor status` shows the account and `/cursor logout` removes the stored key.
|
|
31
|
+
|
|
32
|
+
`CURSOR_API_KEY` overrides the stored login. The key is read by the SDK, not copied into Pi's `auth.json`.
|
|
33
|
+
|
|
34
|
+
Cursor bills SDK traffic under its own terms. This extension cannot tell you whether a run is plan-included, so check the Cursor dashboard for the account's SDK usage.
|
|
35
|
+
|
|
36
|
+
## Use
|
|
37
|
+
|
|
38
|
+
```text
|
|
39
|
+
/model cursor/gpt-5.5
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The model list comes from `Cursor.models.list()`, cached after the last successful read in `~/.pi/agent/pi-cursor-models.json` (0600, keyed by the credential). Startup registers the cache with no network call, the session start refresh replaces it, and a small built-in list is the fallback when there is no cache yet. A model that offers several context windows is registered once per window: the plain id uses the smallest one, `cursor/gpt-5.5@1m` asks for 1M. Cursor bills the larger windows as Max Mode, so the small default is the cheap one. `/cursor models` prints them.
|
|
43
|
+
|
|
44
|
+
`/cursor fast on` adds Cursor's `fast` model parameter to every model that exposes it. It is a billing choice, so it stays off until you ask for it. `/cursor status` shows the current setting.
|
|
45
|
+
|
|
46
|
+
## How it works
|
|
47
|
+
|
|
48
|
+
| Pi | Cursor SDK |
|
|
49
|
+
| ------------------------- | ------------------------------------------------------------------------------------ |
|
|
50
|
+
| Pi system prompt | `AgentOptions.systemPrompt`, replaces the Cursor harness prompt |
|
|
51
|
+
| Pi tools | `LocalAgentOptions.customTools`, one in-process callback per Pi tool |
|
|
52
|
+
| Cursor built-ins | `AgentOptions.tools: ['mcp']`, so only Pi's custom tools exist |
|
|
53
|
+
| Cursor rules, skills, MCP | `local.settingSources: []` |
|
|
54
|
+
| Pi tool execution | the custom tool callback parks, Pi runs the tool, the next provider call resolves it |
|
|
55
|
+
|
|
56
|
+
A tool call does not end the Cursor run. The callback waits, Pi executes the named tool through its normal pipeline, and the next `streamSimple` call resolves the callback with the result. The same Cursor run continues, so the model sees the tool result in the same conversation. A message you steer in while that tool is running is delivered with `Run.steer`, so the model reads it before its next step; images attached to such a message become a one-line note because steering carries text only.
|
|
57
|
+
|
|
58
|
+
One Cursor agent runs per Pi session. A normal turn sends only the new user message. A tool round resolves parked callbacks and sends nothing. The agent is only replaced when Pi's prompt, tool set or working directory changes, or when the Pi history diverges. That replacement replays the existing Pi conversation once as a single message.
|
|
59
|
+
|
|
60
|
+
A restarted Pi process resumes the same Cursor agent instead of replaying. At the end of every clean turn the extension records the agent id with the working folder, prompt and tool hashes, the Pi message count and the extension's hash of that prefix, in `~/.pi/agent/pi-cursor-agents.json`. The next process calls `Agent.resume` when all of those still match and the pending turn is a single new user message. A stale id, a fork that diverged, or a turn that was killed mid tool round all fall back to the replay, which is the pre-resume behavior. The ledger keeps the last 20 sessions. `/cursor clear`, `/cursor login` and `/cursor logout` delete it, so those commands really do start from a fresh agent.
|
|
61
|
+
|
|
62
|
+
There is no HTTP MCP server, no Hono server and no tool-name rewriting. Cursor's SDK invokes the callback directly.
|
|
63
|
+
|
|
64
|
+
## Token and cache behavior
|
|
65
|
+
|
|
66
|
+
Cursor's backend owns its own conversation and cache. Pi does not replay a linear conversation on every turn, it does not run a second agent for tool rounds, and a restart resumes the agent rather than replaying. The Pi system prompt is stable for the lifetime of an agent, and the tool list is stable too. A divergence is the only case that pays a replay.
|
|
67
|
+
|
|
68
|
+
Thinking levels map to Cursor model parameters. For Claude models the extension sets both `thinking` and `effort`. For GPT models it sets `reasoning`. For Grok it sets `effort`. The mapping comes from the live model catalog.
|
|
69
|
+
|
|
70
|
+
What the wire actually costs, measured on the account this extension was built on (gpt-5.5 and auto-smart, thinking off):
|
|
71
|
+
|
|
72
|
+
| Call | Input tokens | Wall time |
|
|
73
|
+
| ----------------------- | -------------------------- | --------- |
|
|
74
|
+
| first call of an agent | 11.9k fresh + 2.6k cached | 4.8-5.5 s |
|
|
75
|
+
| plain follow-up turn | 12.9k fresh + 12.7k cached | 2.2 s |
|
|
76
|
+
| call after a tool round | 36.9k fresh + 36.0k cached | 4.4-13 s |
|
|
77
|
+
|
|
78
|
+
The tool-round number is Cursor's, not the tool result: the SDK re-prefills its own context around the custom tool callback, so one tool call costs about three plain calls. A turn that ends in a tool call is the slow turn, and there is no Pi-side switch for it. The same 32k fresh appears when the working directory is empty, so it is not workspace scanning. Fewer, wider tool calls per turn is the lever that exists.
|
|
79
|
+
|
|
80
|
+
## Limitations
|
|
81
|
+
|
|
82
|
+
- Cursor owns the agent loop and its context management. Pi's compaction does not reach inside a live Cursor agent.
|
|
83
|
+
- `AgentOptions.systemPrompt` is server-gated. A rejected prompt comes back as a failed run about 20 seconds in, not from `Agent.create`, so the extension retries that turn with the prompt prepended to the first message. The rejection is recorded as `noSystemPrompt` in `~/.pi/agent/pi-cursor.json` and every later agent skips the doomed attempt. Clear that flag with `/cursor login`, or edit the file. `/cursor status` shows which path is in use. The fallback works but spends more tokens because Cursor's harness prompt remains.
|
|
84
|
+
- A failed Cursor run reaches Pi as an error message, so an empty answer now means a broken transport, not a silent backend rejection.
|
|
85
|
+
- Usage tokens come from Cursor's `turn-ended` events, plus the run's own total when it ends. Pi records each message's share of the run, so the numbers add up across a tool round instead of keeping only the last step. The message that ends in a tool call shows zero because that step has not ended server-side yet, and the next message carries both steps. Pi shows a zero money cost because Cursor bills outside Pi.
|
|
86
|
+
- Images ride with the message that carries them. A replay replaces every earlier image with an `[image: mime]` placeholder and keeps only the pending message's images, so reattach one to ask about it again after a restart.
|
|
87
|
+
- A model id that Cursor no longer serves fails at `send`, not at model selection.
|
|
88
|
+
- A long Pi tool run is held open by Cursor local runtime. The SDK does not document a timeout for custom tools.
|
|
89
|
+
- The Cursor SDK is a 25 MB dependency with optional platform packages.
|
|
90
|
+
|
|
91
|
+
## Configuration
|
|
92
|
+
|
|
93
|
+
| Variable | Meaning |
|
|
94
|
+
| ---------------- | ----------------------------------------------- |
|
|
95
|
+
| `CURSOR_API_KEY` | Cursor API key. Overrides the stored SDK login. |
|
|
96
|
+
|
|
97
|
+
`~/.pi/agent/pi-cursor.json` holds the two preferences: `fast` from `/cursor fast`, and `noSystemPrompt` once Cursor has refused the Pi prompt for this account.
|
|
98
|
+
|
|
99
|
+
## Tests
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
bun test extensions/pi-cursor
|
|
103
|
+
bun run typecheck
|
|
104
|
+
bun run lint:anti-slop
|
|
105
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tduyng/pi-cursor",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "Use Cursor models in Pi through the official Cursor SDK, with Pi's own prompt and tools.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi",
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi-extension",
|
|
9
|
+
"pi-coding-agent",
|
|
10
|
+
"cursor",
|
|
11
|
+
"cursor-sdk",
|
|
12
|
+
"models"
|
|
13
|
+
],
|
|
14
|
+
"license": "Apache-2.0",
|
|
15
|
+
"author": "tduyng",
|
|
16
|
+
"type": "module",
|
|
17
|
+
"files": [
|
|
18
|
+
"src",
|
|
19
|
+
"!src/**/*.test.ts",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@cursor/sdk": "1.0.40",
|
|
25
|
+
"ata-validator": "^1.62.1",
|
|
26
|
+
"zod": "^4.0.0"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"@earendil-works/pi-ai": "*",
|
|
30
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
31
|
+
},
|
|
32
|
+
"pi": {
|
|
33
|
+
"extensions": [
|
|
34
|
+
"./src/index.ts"
|
|
35
|
+
]
|
|
36
|
+
},
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "git+https://gitlab.com/tduyng/pi-agent.git",
|
|
40
|
+
"directory": "extensions/pi-cursor"
|
|
41
|
+
},
|
|
42
|
+
"homepage": "https://gitlab.com/tduyng/pi-agent/-/tree/main/extensions/pi-cursor#readme",
|
|
43
|
+
"bugs": "https://gitlab.com/tduyng/pi-agent/-/issues"
|
|
44
|
+
}
|
package/src/catalog.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { getAgentDir } from '@earendil-works/pi-coding-agent'
|
|
5
|
+
import { Validator, type Infer } from 'ata-validator'
|
|
6
|
+
import { t } from 'ata-validator/t'
|
|
7
|
+
|
|
8
|
+
import type { ModelInfo } from './models.js'
|
|
9
|
+
|
|
10
|
+
const ParameterValue = t.object({ value: t.string(), displayName: t.optional(t.string()) })
|
|
11
|
+
const Parameter = t.object({
|
|
12
|
+
id: t.string(),
|
|
13
|
+
displayName: t.optional(t.string()),
|
|
14
|
+
values: t.array(ParameterValue)
|
|
15
|
+
})
|
|
16
|
+
const Variant = t.object({
|
|
17
|
+
params: t.array(t.object({ id: t.string(), value: t.string() })),
|
|
18
|
+
displayName: t.string(),
|
|
19
|
+
isDefault: t.optional(t.boolean())
|
|
20
|
+
})
|
|
21
|
+
const CachedModel = t.object({
|
|
22
|
+
id: t.string(),
|
|
23
|
+
displayName: t.string(),
|
|
24
|
+
parameters: t.optional(t.array(Parameter)),
|
|
25
|
+
variants: t.optional(t.array(Variant))
|
|
26
|
+
})
|
|
27
|
+
const CachedCatalog = t.object({ key: t.string(), models: t.array(CachedModel) })
|
|
28
|
+
|
|
29
|
+
const isCatalog = new Validator(CachedCatalog).isValidObject
|
|
30
|
+
|
|
31
|
+
export type KnownCatalog = Infer<typeof CachedCatalog>
|
|
32
|
+
|
|
33
|
+
function cachePath(): string {
|
|
34
|
+
return join(getAgentDir(), 'pi-cursor-models.json')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function parseCatalog(text: string, key: string): ModelInfo[] | undefined {
|
|
38
|
+
try {
|
|
39
|
+
const parsed: unknown = JSON.parse(text)
|
|
40
|
+
if (!isCatalog(parsed) || parsed.key !== key) return undefined
|
|
41
|
+
return parsed.models
|
|
42
|
+
} catch {
|
|
43
|
+
return undefined
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function readCatalog(key: string): ModelInfo[] | undefined {
|
|
48
|
+
try {
|
|
49
|
+
return parseCatalog(readFileSync(cachePath(), 'utf8'), key)
|
|
50
|
+
} catch {
|
|
51
|
+
return undefined
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function writeCatalog(key: string, models: ModelInfo[]): void {
|
|
56
|
+
const path = cachePath()
|
|
57
|
+
const temp = `${path}.${process.pid}.tmp`
|
|
58
|
+
const catalog: KnownCatalog = {
|
|
59
|
+
key,
|
|
60
|
+
models: models.map((model) => ({
|
|
61
|
+
id: model.id,
|
|
62
|
+
displayName: model.displayName,
|
|
63
|
+
parameters: model.parameters,
|
|
64
|
+
variants: model.variants
|
|
65
|
+
}))
|
|
66
|
+
}
|
|
67
|
+
writeFileSync(temp, JSON.stringify(catalog), { mode: 0o600 })
|
|
68
|
+
renameSync(temp, path)
|
|
69
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import type { SdkLoginOptions } from '@cursor/sdk'
|
|
2
|
+
import type { ExtensionAPI, ExtensionCommandContext } from '@earendil-works/pi-coding-agent'
|
|
3
|
+
|
|
4
|
+
import { fallbackModels, rememberModels, toPiModels, type PiModelEntry } from './models.js'
|
|
5
|
+
import { readCatalog, writeCatalog } from './catalog.js'
|
|
6
|
+
import { cursorApiKey, cursorSdk } from './sdk.js'
|
|
7
|
+
import { dropAllRecords } from './resume.js'
|
|
8
|
+
import { noSystemPrompt, patchState } from './state.js'
|
|
9
|
+
import { allSessions, dropSessions, sweep } from './session.js'
|
|
10
|
+
import { createRuntime, streamCursor } from './turn.js'
|
|
11
|
+
|
|
12
|
+
const PROVIDER_ID = 'cursor'
|
|
13
|
+
const API_ID = 'cursor'
|
|
14
|
+
const IDLE_MS = 20 * 60_000
|
|
15
|
+
|
|
16
|
+
export default function piCursor(pi: ExtensionAPI): void {
|
|
17
|
+
const runtime = createRuntime()
|
|
18
|
+
const catalogKey = () => cursorApiKey() ?? 'stored-login'
|
|
19
|
+
const cached = readCatalog(catalogKey())
|
|
20
|
+
let models: PiModelEntry[] = cached && cached.length > 0 ? toPiModels(cached) : fallbackModels()
|
|
21
|
+
if (cached && cached.length > 0) rememberModels(cached)
|
|
22
|
+
let refreshing: Promise<PiModelEntry[]> | undefined
|
|
23
|
+
let refreshed = false
|
|
24
|
+
let sweeper: ReturnType<typeof setInterval> | undefined
|
|
25
|
+
|
|
26
|
+
function register(next: PiModelEntry[]): void {
|
|
27
|
+
models = next
|
|
28
|
+
pi.registerProvider(PROVIDER_ID, {
|
|
29
|
+
name: 'Cursor (SDK)',
|
|
30
|
+
baseUrl: 'cursor://local',
|
|
31
|
+
apiKey: 'cursor-sdk',
|
|
32
|
+
api: API_ID,
|
|
33
|
+
models: next,
|
|
34
|
+
streamSimple: (model, context, options) => streamCursor(runtime, model, context, options),
|
|
35
|
+
refreshModels: () => refresh()
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function refresh(): Promise<PiModelEntry[]> {
|
|
40
|
+
refreshing ??= (async () => {
|
|
41
|
+
try {
|
|
42
|
+
const { Cursor } = await cursorSdk()
|
|
43
|
+
const items = await Cursor.models.list({ apiKey: cursorApiKey() })
|
|
44
|
+
rememberModels(items)
|
|
45
|
+
writeCatalog(catalogKey(), items)
|
|
46
|
+
const next = toPiModels(items)
|
|
47
|
+
if (next.length > 0) models = next
|
|
48
|
+
return models
|
|
49
|
+
} catch {
|
|
50
|
+
return models
|
|
51
|
+
} finally {
|
|
52
|
+
refreshing = undefined
|
|
53
|
+
}
|
|
54
|
+
})()
|
|
55
|
+
return refreshing
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
register(models)
|
|
59
|
+
|
|
60
|
+
if (!sweeper) {
|
|
61
|
+
sweeper = setInterval(() => sweep(runtime.sessions, IDLE_MS), 60_000)
|
|
62
|
+
sweeper.unref()
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
pi.on('session_start', () => {
|
|
66
|
+
if (refreshed) return
|
|
67
|
+
refreshed = true
|
|
68
|
+
void refresh().catch(() => undefined)
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
pi.on('session_shutdown', () => {
|
|
72
|
+
dropSessions(runtime.sessions)
|
|
73
|
+
if (sweeper) clearInterval(sweeper)
|
|
74
|
+
sweeper = undefined
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
process.once('exit', () => dropSessions(runtime.sessions))
|
|
78
|
+
|
|
79
|
+
const show = (text: string) =>
|
|
80
|
+
pi.sendMessage({ customType: 'cursor', display: true, content: text }, { triggerTurn: false })
|
|
81
|
+
|
|
82
|
+
async function login(ctx: ExtensionCommandContext): Promise<void> {
|
|
83
|
+
const { Cursor } = await cursorSdk()
|
|
84
|
+
const options: SdkLoginOptions = {
|
|
85
|
+
apiKeyName: 'pi-cursor',
|
|
86
|
+
onLoginUrl: (url) => {
|
|
87
|
+
void show(`Cursor login. Open this URL if the browser did not:\n${url}`)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (ctx.signal) options.signal = ctx.signal
|
|
91
|
+
const result = await Cursor.auth.login(options)
|
|
92
|
+
patchState({ noSystemPrompt: false })
|
|
93
|
+
dropAllRecords()
|
|
94
|
+
register(await refresh())
|
|
95
|
+
await show(
|
|
96
|
+
`Cursor: logged in${result.email ? ` as ${result.email}` : ''}. ${models.length} model(s) available.`
|
|
97
|
+
)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
pi.registerCommand('cursor', {
|
|
101
|
+
description: 'Cursor SDK login, status and model list',
|
|
102
|
+
getArgumentCompletions: (prefix: string) =>
|
|
103
|
+
[
|
|
104
|
+
{ value: 'status', label: 'status', description: 'login state, models and live agents' },
|
|
105
|
+
{ value: 'login', label: 'login', description: 'browser login, no Cursor CLI' },
|
|
106
|
+
{ value: 'logout', label: 'logout', description: 'forget the SDK credential' },
|
|
107
|
+
{ value: 'models', label: 'models', description: 'every Cursor model the provider exposes' },
|
|
108
|
+
{ value: 'clear', label: 'clear', description: 'close every warm Cursor agent' },
|
|
109
|
+
{ value: 'fast', label: 'fast', description: 'toggle cursor fast mode: fast on|off' },
|
|
110
|
+
{ value: 'help', label: 'help', description: 'usage' }
|
|
111
|
+
].filter((item) => item.value.startsWith(prefix.trim())),
|
|
112
|
+
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
113
|
+
const sub = args.trim().split(/\s+/).filter(Boolean)[0] ?? 'status'
|
|
114
|
+
if (sub === 'login') {
|
|
115
|
+
await login(ctx)
|
|
116
|
+
return
|
|
117
|
+
}
|
|
118
|
+
if (sub === 'logout') {
|
|
119
|
+
const { Cursor } = await cursorSdk()
|
|
120
|
+
await Cursor.auth.logout()
|
|
121
|
+
dropAllRecords()
|
|
122
|
+
rememberModels([])
|
|
123
|
+
register(fallbackModels())
|
|
124
|
+
await show('Cursor: logged out. The SDK credential is gone.')
|
|
125
|
+
return
|
|
126
|
+
}
|
|
127
|
+
if (sub === 'clear') {
|
|
128
|
+
dropSessions(runtime.sessions)
|
|
129
|
+
dropAllRecords()
|
|
130
|
+
await show('Cursor: closed every warm agent.')
|
|
131
|
+
return
|
|
132
|
+
}
|
|
133
|
+
if (sub === 'fast') {
|
|
134
|
+
const value = args.trim().split(/\s+/).filter(Boolean)[1]
|
|
135
|
+
if (value !== 'on' && value !== 'off') {
|
|
136
|
+
await show(`Cursor fast mode is ${runtime.fast ? 'on' : 'off'}. Use /cursor fast on|off.`)
|
|
137
|
+
return
|
|
138
|
+
}
|
|
139
|
+
runtime.fast = value === 'on'
|
|
140
|
+
patchState({ fast: runtime.fast })
|
|
141
|
+
await show(`Cursor fast mode ${runtime.fast ? 'on' : 'off'} for models that expose it.`)
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
if (sub === 'models') {
|
|
145
|
+
await show(
|
|
146
|
+
[
|
|
147
|
+
`${models.length} model(s), provider id ${PROVIDER_ID}:`,
|
|
148
|
+
...models.map((model) => ` ${PROVIDER_ID}/${model.id}`)
|
|
149
|
+
].join('\n')
|
|
150
|
+
)
|
|
151
|
+
return
|
|
152
|
+
}
|
|
153
|
+
if (sub === 'help') {
|
|
154
|
+
await show(
|
|
155
|
+
[
|
|
156
|
+
'Usage: /cursor [status|login|logout|models|clear|fast|help]',
|
|
157
|
+
'',
|
|
158
|
+
'Login uses the official Cursor SDK browser flow and mints a stored API key.',
|
|
159
|
+
'No Cursor CLI is installed or called.',
|
|
160
|
+
'Pick a model with /model, for example cursor/gpt-5.5.',
|
|
161
|
+
'CURSOR_API_KEY overrides the stored SDK login.',
|
|
162
|
+
'Models default to their smallest context window. Pick /model cursor/gpt-5.5@1m for the 1M one.',
|
|
163
|
+
].join('\n')
|
|
164
|
+
)
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
let authLine = 'unknown'
|
|
168
|
+
try {
|
|
169
|
+
const { Cursor } = await cursorSdk()
|
|
170
|
+
const auth = await Cursor.auth.status()
|
|
171
|
+
authLine =
|
|
172
|
+
auth.status === 'logged-in' ? `logged-in${auth.email ? ` (${auth.email})` : ''}` : auth.status
|
|
173
|
+
} catch (error) {
|
|
174
|
+
authLine = `unavailable: ${error instanceof Error ? error.message : String(error)}`
|
|
175
|
+
}
|
|
176
|
+
const sessions = allSessions(runtime.sessions)
|
|
177
|
+
const parked = sessions.reduce((count, session) => count + session.parked.size, 0)
|
|
178
|
+
await show(
|
|
179
|
+
[
|
|
180
|
+
`auth: ${authLine}`,
|
|
181
|
+
`credential: ${cursorApiKey() ? 'CURSOR_API_KEY' : 'stored SDK login'}`,
|
|
182
|
+
`models: ${models.length}`,
|
|
183
|
+
`live agents: ${sessions.length}, parked tool calls: ${parked}`,
|
|
184
|
+
`system prompt: ${
|
|
185
|
+
noSystemPrompt()
|
|
186
|
+
? 'not enabled for this account, Pi prompt rides in the first message'
|
|
187
|
+
: 'sent as AgentOptions.systemPrompt'
|
|
188
|
+
}`,
|
|
189
|
+
`fast mode: ${runtime.fast ? 'on' : 'off'}`,
|
|
190
|
+
'prompt: Pi system prompt and Pi tools only; Cursor built-in tools disabled'
|
|
191
|
+
].join('\n')
|
|
192
|
+
)
|
|
193
|
+
}
|
|
194
|
+
})
|
|
195
|
+
}
|
package/src/json.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
import { Validator } from 'ata-validator'
|
|
4
|
+
import { t } from 'ata-validator/t'
|
|
5
|
+
|
|
6
|
+
const isStringArray = new Validator(t.array(t.string())).isValidObject
|
|
7
|
+
const isString = new Validator(t.string()).isValidObject
|
|
8
|
+
const isNumber = new Validator(t.number()).isValidObject
|
|
9
|
+
const isBoolean = new Validator(t.boolean()).isValidObject
|
|
10
|
+
|
|
11
|
+
export type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject
|
|
12
|
+
export type JsonObject = { [key: string]: JsonValue }
|
|
13
|
+
|
|
14
|
+
const ObjectSchema = t.object({}, { additionalProperties: true })
|
|
15
|
+
const isObjectSchema = new Validator(ObjectSchema).isValidObject
|
|
16
|
+
const ArraySchema = t.array(t.any())
|
|
17
|
+
const isArraySchema = new Validator(ArraySchema).isValidObject
|
|
18
|
+
|
|
19
|
+
function isJsonObject<V>(value: V): value is V & JsonObject {
|
|
20
|
+
return isObjectSchema(value) && !Array.isArray(value)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function jsonObject(value: JsonValue | undefined): JsonObject | undefined {
|
|
24
|
+
return isJsonObject(value) ? value : undefined
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function jsonArray(value: JsonValue | undefined): JsonValue[] | undefined {
|
|
28
|
+
if (!isArraySchema(value)) return undefined
|
|
29
|
+
return value
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function jsonStrings(value: JsonValue | undefined): string[] | undefined {
|
|
33
|
+
if (!isStringArray(value)) return undefined
|
|
34
|
+
return value
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function jsonText(object: JsonObject, key: string): string | undefined {
|
|
38
|
+
const value = object[key]
|
|
39
|
+
return isString(value) ? value : undefined
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function jsonNumber(object: JsonObject, key: string): number | undefined {
|
|
43
|
+
const value = object[key]
|
|
44
|
+
return isNumber(value) ? value : undefined
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function jsonBoolean(object: JsonObject, key: string): boolean | undefined {
|
|
48
|
+
const value = object[key]
|
|
49
|
+
return isBoolean(value) ? value : undefined
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function jsonFlag(object: JsonObject, key: string): boolean {
|
|
53
|
+
return jsonBoolean(object, key) === true
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function stableStringify(value: JsonValue): string {
|
|
57
|
+
return JSON.stringify(sortValue(value))
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function sortValue(value: JsonValue): JsonValue {
|
|
61
|
+
if (Array.isArray(value)) return value.map(sortValue)
|
|
62
|
+
const object = jsonObject(value)
|
|
63
|
+
if (!object) return value
|
|
64
|
+
const sorted: JsonObject = {}
|
|
65
|
+
for (const key of Object.keys(object).toSorted()) {
|
|
66
|
+
const item = object[key]
|
|
67
|
+
if (item !== undefined) sorted[key] = sortValue(item)
|
|
68
|
+
}
|
|
69
|
+
return sorted
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function sha(value: string): string {
|
|
73
|
+
return createHash('sha256').update(value).digest('base64url')
|
|
74
|
+
}
|