pi-cursor-sdk 0.1.16 → 0.1.17

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +29 -1
  2. package/README.md +1 -1
  3. package/docs/cursor-live-smoke-checklist.md +35 -39
  4. package/docs/cursor-model-ux-spec.md +3 -2
  5. package/package.json +11 -5
  6. package/scripts/steering-rpc-smoke.mjs +238 -0
  7. package/scripts/tmux-live-smoke.sh +418 -0
  8. package/scripts/validate-smoke-jsonl.mjs +152 -0
  9. package/src/cursor-edit-diff.ts +11 -0
  10. package/src/cursor-env-boolean.ts +22 -0
  11. package/src/cursor-live-run-coordinator.ts +483 -0
  12. package/src/cursor-native-tool-display-registration.ts +93 -0
  13. package/src/cursor-native-tool-display-replay.ts +465 -0
  14. package/src/cursor-native-tool-display-state.ts +78 -0
  15. package/src/cursor-native-tool-display-tools.ts +102 -0
  16. package/src/cursor-native-tool-display.ts +10 -648
  17. package/src/cursor-partial-content-emitter.ts +121 -0
  18. package/src/cursor-pi-tool-bridge-abort.ts +133 -0
  19. package/src/cursor-pi-tool-bridge-diagnostics.ts +179 -0
  20. package/src/cursor-pi-tool-bridge-mcp.ts +118 -0
  21. package/src/cursor-pi-tool-bridge-run.ts +384 -0
  22. package/src/cursor-pi-tool-bridge-server.ts +182 -0
  23. package/src/cursor-pi-tool-bridge-snapshot.ts +88 -0
  24. package/src/cursor-pi-tool-bridge-types.ts +80 -0
  25. package/src/cursor-pi-tool-bridge.ts +42 -1104
  26. package/src/cursor-provider-live-run-drain.ts +379 -0
  27. package/src/cursor-provider-turn-coordinator.ts +456 -0
  28. package/src/cursor-provider.ts +72 -1103
  29. package/src/cursor-record-utils.ts +26 -0
  30. package/src/cursor-sdk-output-filter.ts +100 -0
  31. package/src/cursor-sensitive-text.ts +37 -0
  32. package/src/cursor-tool-transcript.ts +28 -1229
  33. package/src/cursor-transcript-tool-formatters.ts +641 -0
  34. package/src/cursor-transcript-tool-specs.ts +441 -0
  35. package/src/cursor-transcript-utils.ts +276 -0
package/CHANGELOG.md CHANGED
@@ -1,6 +1,34 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.1.17 - 2026-05-23
4
+
5
+ ### Added
6
+
7
+ - Surface in-progress Cursor SDK `task` activity in the TUI from SDK-provided `args.description`, with one deduped line such as `Cursor task: Explore AI/automation projects` and no generic heartbeat or per-tool start spam.
8
+
9
+ ### Changed
10
+
11
+ - Bump pi dev dependency baseline to `0.75.5` for read-tool collapsed-card rendering, package update fixes, and other upstream pi changes. Cursor edit replay remains display-only via `diffString`; pi's new SDK `details.patch` field is not required because Cursor agents do not execute pi's edit tool.
12
+ - Rework live-run internals into dedicated coordination/drain/turn/partial-content modules (`cursor-live-run-coordinator.ts`, `cursor-provider-live-run-drain.ts`, `cursor-provider-turn-coordinator.ts`, `cursor-partial-content-emitter.ts`) while preserving the provider's external contract.
13
+ - Complete phase-2 remediation for #23/#24/#25 by splitting bridge ownership across snapshot/server/run/abort/diagnostics/MCP/types modules, splitting native replay ownership across state/registration/replay/tools modules, and unifying tool completion routing through `resolveToolCompletion`.
14
+ - Replace monolithic provider test coverage with focused stream/bridge/replay/live-run suites plus shared harness helpers.
15
+ - Promote smoke automation into packaged entrypoints (`npm run smoke:live`, `npm run smoke:steering`, `npm run smoke:jsonl`) and make helper retry/polling behavior explicit (TUI answer/footer polling plus deterministic tmux cleanup).
16
+ - Document the hard maintainer rule that Cursor SDK behavior must be verified against the installed `@cursor/sdk` package and/or official TypeScript SDK docs before implementation or release claims.
17
+ - Bump package metadata to `0.1.17` so the dry-run tarball no longer collides with the existing `v0.1.16` tag.
18
+
19
+ ### Fixed
20
+
21
+ - Resolve startup noise issue #17 by extending Cursor SDK bootstrap filtering to late hook compatibility warnings and ripgrep/ignore-mapping output while preserving non-startup logs.
22
+ - Fix steering/follow-up delivery for active pooled Cursor runs by resuming/waiting on the in-flight run and sending incremental follow-up text after pending tool/result flow completes instead of issuing a second concurrent `Agent.send()`; additional stale tool batches from the old run are cancelled so the new user input is not lost.
23
+ - Resolve issue #19 with a canonical edit-diff fallback resolver (`diffString → diff → unifiedDiff → patch`) shared by replay and transcript formatting paths.
24
+ - Resolve issue #20 by updating the token-tracking investigation note to mark the `0.75.3` observation as point-in-time and call out the current `0.75.5` development baseline.
25
+ - Resolve issue #21 by decomposing prior 1k+ provider/transcript/bridge/test monoliths into ownership-scoped modules.
26
+ - Harden bridge diagnostics and secret scrubbing so debug JSONL stays run-safe and allowlisted without endpoint path material, raw args/results, or credential payloads.
27
+ - Make Cursor SDK output filtering safe for overlapping provider streams by restoring the global stdout/stderr/console patch only after the last active install.
28
+ - Reject bridge MCP calls cleanly when tool-dispatch handlers throw, and avoid suppressing unrelated MCP replay solely because an external payload reuses a known bridge request ID.
29
+ - Bound native replay diff/write previews by both lines and characters, summarize non-text MCP content without dumping raw payload JSON, and make expanded-diff truncation copy truthful.
30
+ - Change smoke forbidden-material scans to report only matching file names, not secret-bearing matched lines.
31
+ - Harden live-smoke direct-output checks so a step logs `PASS` only after both command exit and expected stdout assertion succeed, with the basic prompt retrying once on empty output even when the first command exits zero.
4
32
 
5
33
  ## 0.1.16 - 2026-05-22
6
34
 
package/README.md CHANGED
@@ -248,7 +248,7 @@ Actual Cursor runs still need a key from `/login`, `CURSOR_API_KEY`, or `--api-k
248
248
  - **The pi tool bridge is local and MCP-backed.** Bridgeable active pi tools are exposed to local Cursor agents through a tokenized `127.0.0.1` MCP endpoint; internal Cursor replay activity names are excluded, and overlapping built-in pi tools are hidden by default. Set `PI_CURSOR_PI_TOOL_BRIDGE=0` to disable it or `PI_CURSOR_EXPOSE_BUILTIN_TOOLS=1` to expose overlapping built-ins too.
249
249
  - **Cursor native tool replay is display-only.** Replay renders recorded Cursor SDK activity and never re-runs Cursor-side commands, reapplies Cursor edits, calls MCP servers, or mutates pi state. Workflow tools such as Cursor `SwitchMode` and Cursor todo state are not pi workflow controls. See [Cursor native tool replay](docs/cursor-native-tool-replay.md) for supported replay cards, ordering, conflict handling, and opt-out flags.
250
250
  - **Cursor run state can span tool-use turns.** Within a pi session, the extension reuses one Cursor SDK agent across compatible follow-up turns and sends incremental prompts when context still matches. It recreates the agent when context diverges, after compaction or `/tree` navigation, on API key changes, after send errors, or on session shutdown. For bridged pi tools, the matching pi `toolResult` resolves into the same live Cursor SDK run without creating a new `Agent`, unless the run was disposed, aborted, or cancelled. Replay can also split one live Cursor SDK run across pi `toolUse` turns for display.
251
- - **Cursor setting sources default to all.** The extension passes `local.settingSources: ["all"]` by default so configured Cursor MCP servers, plugin tools, project/user settings, and related Cursor-native capabilities are available like they are in Cursor. To narrow loading, set a comma-separated list such as `PI_CURSOR_SETTING_SOURCES=project,user,plugins`. To disable ambient setting sources, set `PI_CURSOR_SETTING_SOURCES=none`. Direct Cursor SDK startup logs are suppressed so setting/skill loading messages do not pollute the TUI.
251
+ - **Cursor setting sources default to all.** The extension passes `local.settingSources: ["all"]` by default so configured Cursor MCP servers, plugin tools, project/user settings, and related Cursor-native capabilities are available like they are in Cursor. To narrow loading, set a comma-separated list such as `PI_CURSOR_SETTING_SOURCES=project,user,plugins`. To disable ambient setting sources, set `PI_CURSOR_SETTING_SOURCES=none`. Direct Cursor SDK bootstrap logs (settings, skills, hook-load compatibility warnings, and similar) are suppressed so they do not pollute the TUI.
252
252
  - **Max Mode is not a manual pi variant.** Cursor's SDK may enable Max Mode automatically for models that require it. This extension only advertises exact context-window variants that the SDK catalog exposes and otherwise uses conservative SDK-derived default/non-Max context windows.
253
253
  - **Output token limits are conservative.** Cursor SDK model metadata does not currently expose output token limits directly.
254
254
  - **Token usage is approximate in pi.** Cursor SDK usage events include cumulative internal agent/tool/cache work, so raw Cursor SDK counters are not copied into pi usage. The extension reports approximate pi session activity in `input`/`output`, including split-run tool calls and consumed tool results, while `totalTokens` tracks the replayable Cursor prompt/context estimate used for context display and compaction.
@@ -22,6 +22,14 @@ mkdir -p "$SMOKE_DIR"
22
22
  pi -e . --list-models cursor
23
23
  ```
24
24
 
25
+ The repo also ships partial automation for the prerequisite/basic/default-settings/non-interactive math/TUI output polling/steering/diagnostic/JSONL subset:
26
+
27
+ ```bash
28
+ npm run smoke:live
29
+ ```
30
+
31
+ The script is a helper only; it polls the section 3 TUI for answer/footer evidence and then cleans up the tmux session, but it does not replace manual visual review of the full TUI checklist. Release readiness still requires the manual checks below for detailed TUI behavior, bridge, standalone native replay, abort/cancel, packaging, cleanup, and any touched runtime surface not covered by the helper.
32
+
25
33
  Pass criteria:
26
34
 
27
35
  - `cursor/composer-2.5` appears in the model list.
@@ -155,13 +163,25 @@ Forbidden fields:
155
163
  Run a forbidden-material scan over smoke stderr/captures:
156
164
 
157
165
  ```bash
158
- find "$SMOKE_DIR" -type f \( -name '*stderr.txt' -o -name 'capture*.txt' \) -print0 |
159
- xargs -0 grep -E 'CURSOR_API_KEY|Bearer [A-Za-z0-9._-]+|/cursor-pi-tool-bridge/[^ ]+/mcp|127\.0\.0\.1:[0-9]+/cursor-pi-tool-bridge|apiKey|cookie|session-cookie|secret-token'
166
+ forbidden_files="$(find "$SMOKE_DIR" -type f \( -name '*stderr.txt' -o -name '*capture*.txt' \) -print0 |
167
+ xargs -0 grep -IlE 'CURSOR_API_KEY|Bearer [A-Za-z0-9._-]+|/cursor-pi-tool-bridge/[^ ]+/mcp|127\.0\.0\.1:[0-9]+/cursor-pi-tool-bridge|apiKey|cookie|session-cookie|secret-token' || true)"
168
+ if [[ -n "$forbidden_files" ]]; then
169
+ printf 'Forbidden material matched in smoke files; inspect locally without pasting matched lines.\n' >&2
170
+ while IFS= read -r file; do
171
+ [[ -z "$file" ]] && continue
172
+ if [[ "$file" == "$SMOKE_DIR/"* ]]; then
173
+ printf ' %s\n' "${file#"$SMOKE_DIR/"}" >&2
174
+ else
175
+ printf ' %s\n' "$file" >&2
176
+ fi
177
+ done <<<"$forbidden_files"
178
+ exit 1
179
+ fi
160
180
  ```
161
181
 
162
182
  Pass criteria:
163
183
 
164
- - The grep returns no matches except deliberately planted test strings that are asserted not to appear in serialized diagnostics.
184
+ - The scan returns no matching files except deliberately planted test strings that are asserted not to appear in serialized diagnostics, and it does not print matched secret-bearing lines.
165
185
  - If tool names themselves are considered sensitive for a release target, do not enable `PI_CURSOR_PI_TOOL_BRIDGE_DEBUG=1` for shared logs. The diagnostics contract intentionally allows tool names.
166
186
 
167
187
  ## 7. Long-running bridge and abort/cancel
@@ -190,45 +210,21 @@ Pass criteria:
190
210
  After all live runs, scan JSONL structurally instead of reading raw content into a report:
191
211
 
192
212
  ```bash
193
- node <<'NODE'
194
- const fs = require('fs');
195
- const path = require('path');
196
- const root = process.env.SMOKE_DIR;
197
- const files = [];
198
- function walk(dir) {
199
- for (const name of fs.readdirSync(dir)) {
200
- const p = path.join(dir, name);
201
- const st = fs.statSync(p);
202
- if (st.isDirectory()) walk(p);
203
- else if (p.endsWith('.jsonl')) files.push(p);
204
- }
205
- }
206
- walk(root);
207
- let failures = 0;
208
- for (const file of files.sort()) {
209
- const records = fs.readFileSync(file, 'utf8').trim().split(/\n+/).filter(Boolean).map(JSON.parse);
210
- const messages = records.filter((record) => record.type === 'message').map((record) => record.message);
211
- const assistants = messages.filter((message) => message.role === 'assistant');
212
- const usage = assistants.map((message) => message.usage).filter(Boolean);
213
- const badUsage = usage.filter((u) =>
214
- typeof u.input !== 'number' || u.input < 0 ||
215
- typeof u.output !== 'number' || u.output < 0 ||
216
- typeof u.totalTokens !== 'number' || u.totalTokens < 0 ||
217
- u.cacheRead !== 0 || u.cacheWrite !== 0
218
- );
219
- if (usage.length !== assistants.length || badUsage.length > 0) failures += 1;
220
- console.log(JSON.stringify({ file: path.relative(root, file), assistantCount: assistants.length, usageCount: usage.length, badUsageCount: badUsage.length }));
221
- }
222
- process.exit(failures === 0 ? 0 : 1);
223
- NODE
213
+ node scripts/validate-smoke-jsonl.mjs "$SMOKE_DIR"
224
214
  ```
225
215
 
226
- Pass criteria:
216
+ Script-enforced pass criteria:
217
+
218
+ - Every scanned JSONL file is parseable and non-empty.
219
+ - Every scanned JSONL file contains at least one assistant message.
220
+ - Every assistant message has usage metadata.
221
+ - Assistant usage `input`, `output`, and `totalTokens` are non-negative numbers.
222
+ - Assistant usage `cacheRead` and `cacheWrite` are exactly `0`.
223
+
224
+ Additional manual usage checks for provider/accounting changes:
227
225
 
228
- - Every assistant message has valid usage.
229
- - Cache fields remain `0`.
230
- - Tool-heavy runs show nonzero output for visible assistant/tool-call activity.
231
- - Split runs count consumed tool-result input once on the following assistant turn.
226
+ - Tool-heavy runs should show nonzero output for visible assistant/tool-call activity.
227
+ - Split runs should count consumed tool-result input once on the following assistant turn.
232
228
 
233
229
  ## 9. Standard local gates
234
230
 
@@ -16,7 +16,7 @@ Current implementation notes:
16
16
  - Image payload forwarding sends images only from the latest user message. If the latest user turn is plain text after an earlier image turn, the transcript keeps an `[image omitted from transcript]` placeholder but no image bytes are sent to Cursor. The prompt explicitly tells Cursor that prior image bytes are unavailable and to ask the user to reattach or describe a prior image when needed. Carrying images forward across turns remains a future product decision because it affects token cost, privacy, stale visual context, and expected multimodal follow-up behavior.
17
17
  - `@cursor/sdk` is a package dependency of this extension; users should not need a global SDK install.
18
18
  - Cursor auth uses pi-native API-key resolution for provider `cursor`: CLI `--api-key`, stored `~/.pi/agent/auth.json` API key from `/login`, then `CURSOR_API_KEY`. The extension config file stores only non-secret Cursor-only state such as fast defaults.
19
- - Local agents pass `settingSources: ["all"]` by default so Cursor MCP servers, plugin tools, project/user settings, and related Cursor-native capabilities are available. Users can narrow loading with a comma-separated list such as `PI_CURSOR_SETTING_SOURCES=project,user,plugins`, or disable ambient setting sources with `PI_CURSOR_SETTING_SOURCES=none`. The provider suppresses direct Cursor SDK startup writes around agent creation so setting/skill loading logs do not pollute pi's TUI.
19
+ - Local agents pass `settingSources: ["all"]` by default so Cursor MCP servers, plugin tools, project/user settings, and related Cursor-native capabilities are available. Users can narrow loading with a comma-separated list such as `PI_CURSOR_SETTING_SOURCES=project,user,plugins`, or disable ambient setting sources with `PI_CURSOR_SETTING_SOURCES=none`. The provider suppresses direct Cursor SDK bootstrap stdout/stderr/console noise (including late first-send workspace loading such as hook compatibility warnings) so it does not pollute pi's TUI.
20
20
  - Cursor SDK models are treated as thinking-capable even when pi reports `thinking=no`; that pi column only means the SDK did not expose a pi-controllable thinking parameter for that model.
21
21
  - Cursor-side thinking remains visible through pi's native thinking rendering when the Cursor SDK emits thinking or summary deltas.
22
22
  - Local Cursor agents get two tool surfaces. First, Cursor keeps the Cursor SDK local-agent tool surface plus configured Cursor settings, plugins, and Cursor MCP servers. Second, pi-cursor-sdk exposes active pi tools through a default-on, tokenized loopback MCP bridge when bridgeable tools exist.
@@ -27,7 +27,7 @@ Current implementation notes:
27
27
  - Cursor SDK MCP tool calls use a guarded timeout override because installed `@cursor/sdk` 1.0.13 has a 60-second MCP request default with no public per-server timeout option. The extension extends that Cursor SDK MCP `callTool` timeout path to 3600 seconds by default. Users can override it with `PI_CURSOR_MCP_TOOL_TIMEOUT_MS` or `PI_CURSOR_MCP_TOOL_TIMEOUT_SECONDS`.
28
28
  - Bridge diagnostics are opt-in only: `PI_CURSOR_PI_TOOL_BRIDGE_DEBUG=1` writes typed, allowlisted, scrubbed single-line JSONL records to `process.stderr` with prefix `[pi-cursor-sdk:bridge]`. Diagnostics are scrubbed operational logs, not anonymous telemetry. They intentionally include tool names, safe correlation IDs, run lifecycle, exposed pi↔MCP name pairs, queued requests, result resolution, rejection, cancellation, and pending counts. Correlation IDs are generated independently from the tokenized endpoint path, and Cursor MCP call IDs are hashed before serialization. Diagnostics must not include endpoint paths/URLs/path components/tokens, API keys, bearer tokens, cookies, session credentials, raw args/results, stdout/stderr payloads, file contents, Cursor settings output, or local private session paths in tracked docs, and they must not call pi UI status, notification, or footer APIs. If tool names themselves are unacceptable for a release target, bridge debug diagnostics are not safe for shared logs under the current contract.
29
29
  - This repo does not provide a generic desktop-automation, browser-driver, or CDP recipe. Provider docs should describe pi-cursor-sdk's Cursor provider/bridge contract only.
30
- - Cursor internal tool activity is recorded from SDK events and scrubbed. In interactive TTY sessions, supported completed `read`, `bash`, `grep`, `find`, `ls`, `edit`, `write`, diagnostics, delete, todo/plan, task, image generation, and MCP activity is replayed through pi's native tool-call rendering path with recorded Cursor results, so the TUI can show native-looking cards without rerunning Cursor's reads/shell commands/file edits. Cursor `glob` activity is replayed through native `find` cards. Cursor write activity is replayed through native-looking `write` cards, and Cursor StrReplace/edit activity uses native-looking `edit` only when recorded arguments truthfully satisfy pi's `edit` schema; path-only Cursor edit and notebook edit replay falls back to neutral Cursor activity before pi validation. Diagnostics, delete, todos/plans, task, image, and MCP activity use neutral Cursor activity cards with pi's default success/error shell. Neutral Cursor activity calls include `activityTitle` and, when available, `activitySummary` so partial/collapsed cards preserve identity such as `Cursor plan`, `Cursor todos`, `Cursor MCP`, or `Cursor edit`. Replay-only tools display recorded Cursor results, normalize workspace-local paths/diff headers for display, use pi diff colors for edit previews and path-inferred syntax highlighting for write previews, and fail closed if called without a recorded result. Native replay wrappers are registered only for tool names not already owned by another extension; conflicting tools use the bounded scrubbed transcript fallback. Cursor workflow tools such as `SwitchMode` and Cursor todo state are not pi workflow controls; reported todo/plan events are displayed as Cursor activity only. Plan/todo replay cards can be followed by Cursor's final plan text, selected from `run.wait().result` when Cursor provides one and trimmed against already-emitted text. Started Cursor SDK tool calls that never receive a completion event are discarded without synthetic replay errors; explicit failures remain visible when Cursor reports them through completed tool calls or step results. `PI_CURSOR_NATIVE_TOOL_DISPLAY=0` disables native replay, and `PI_CURSOR_REGISTER_NATIVE_TOOLS=0` is a registration-only opt-out that keeps the transcript fallback without shadowing pi tool names. When bridge or native replay cards are emitted, the provider mirrors Codex's turn shape as Cursor SDK activity arrives: assistant `toolUse`, pi `toolResult`s, live post-tool Cursor thinking/text, any later tool batches as further `toolUse` turns, then Cursor's final assistant answer. For shell replay, completed `stdout` / `stderr` are primary; unambiguous `shell-output-delta` data is used only as display-only fallback for empty successful shell completions, and overlapping shell calls drop ambiguous deltas instead of guessing. Non-interactive runs keep bounded scrubbed transcript output instead, preserving `pi -p` assistant text output. Cursor text deltas stream live when no live-run turn split is active.
30
+ - Cursor internal tool activity is recorded from SDK events and scrubbed. In interactive TTY sessions, supported completed `read`, `bash`, `grep`, `find`, `ls`, `edit`, `write`, diagnostics, delete, todo/plan, task, image generation, and MCP activity is replayed through pi's native tool-call rendering path with recorded Cursor results, so the TUI can show native-looking cards without rerunning Cursor's reads/shell commands/file edits. Cursor `glob` activity is replayed through native `find` cards. Cursor write activity is replayed through native-looking `write` cards, and Cursor StrReplace/edit activity uses native-looking `edit` only when recorded arguments truthfully satisfy pi's `edit` schema; path-only Cursor edit and notebook edit replay falls back to neutral Cursor activity before pi validation. Diagnostics, delete, todos/plans, task, image, and MCP activity use neutral Cursor activity cards with pi's default success/error shell. Neutral Cursor activity calls include `activityTitle` and, when available, `activitySummary` so partial/collapsed cards preserve identity such as `Cursor plan`, `Cursor todos`, `Cursor MCP`, or `Cursor edit`. When the Cursor SDK emits a running `task` tool call with a description, the provider surfaces one low-noise in-progress line such as `Cursor task: Explore AI/automation projects` from SDK args only; it does not emit generic heartbeat text or per-tool start cards for ordinary `read`, `bash`, or `grep` activity. Replay-only tools display recorded Cursor results, normalize workspace-local paths/diff headers for display, use pi diff colors for edit previews and path-inferred syntax highlighting for write previews, and fail closed if called without a recorded result. Native replay wrappers are registered only for tool names not already owned by another extension; conflicting tools use the bounded scrubbed transcript fallback. Cursor workflow tools such as `SwitchMode` and Cursor todo state are not pi workflow controls; reported todo/plan events are displayed as Cursor activity only. Plan/todo replay cards can be followed by Cursor's final plan text, selected from `run.wait().result` when Cursor provides one and trimmed against already-emitted text. Started Cursor SDK tool calls that never receive a completion event are discarded without synthetic replay errors; explicit failures remain visible when Cursor reports them through completed tool calls or step results. `PI_CURSOR_NATIVE_TOOL_DISPLAY=0` disables native replay, and `PI_CURSOR_REGISTER_NATIVE_TOOLS=0` is a registration-only opt-out that keeps the transcript fallback without shadowing pi tool names. When bridge or native replay cards are emitted, the provider mirrors Codex's turn shape as Cursor SDK activity arrives: assistant `toolUse`, pi `toolResult`s, live post-tool Cursor thinking/text, any later tool batches as further `toolUse` turns, then Cursor's final assistant answer. For shell replay, completed `stdout` / `stderr` are primary; unambiguous `shell-output-delta` data is used only as display-only fallback for empty successful shell completions, and overlapping shell calls drop ambiguous deltas instead of guessing. Non-interactive runs keep bounded scrubbed transcript output instead, preserving `pi -p` assistant text output. Cursor text deltas stream live when no live-run turn split is active.
31
31
  - Synthetic replay names are internal compatibility details. New model-facing prompt text and user-visible cards use native tool names when renderer-compatible, or neutral Cursor activity labels when not. Legacy sessions containing old internal replay names are sanitized before prompt/display. Bridge MCP names such as `pi__sem_reindex` are MCP-only; pi session output uses real pi tool names.
32
32
  - Cursor SDK usage events report cumulative internal agent/tool/cache work, not the replayable pi prompt context. The extension does not copy raw Cursor SDK usage into pi usage or compaction. For Cursor assistant messages, `usage.input`/`usage.output` are approximate pi session activity components: initial Cursor prompt input is counted once, consumed split-run tool results are counted as deduped input on the following assistant turn, and assistant output includes visible text/thinking/tool-call content. `usage.totalTokens` is the replayable Cursor prompt/context estimate derived from the same `buildCursorPrompt()` path used for `Agent.send`; it may differ from `input + output` and is the context-safe value for display/compaction. `src/cursor-usage-accounting.ts` owns this usage policy, and `src/cursor-live-run-accounting.ts` owns prompt-once and consumed-tool-result accounting so provider usage and bridge result resolution share the same matched tool-result boundary.
33
33
  - Audit observation, 2026-05-19, superseded by the 2026-05-21 replay pass: a missing-file read with Composer 2.5 emitted `tool-call-started` for Cursor `read`, then streamed final text `Error: File not found`, but did not emit `tool-call-completed` or an `onStep` `toolCall` error result. Leftover started calls are now discarded at run completion instead of becoming synthetic replay errors. Cursor-reported completed/step errors remain visible.
@@ -37,6 +37,7 @@ Current implementation notes:
37
37
  - Max Mode context windows are distinct from default/non-Max context windows. `@cursor/sdk` 1.0.13 documentation says the SDK may enable Max Mode automatically when a selected model requires it, but the public local-agent `ModelSelection` path still does not expose a manual Max Mode selector. Do not advertise Max Mode context windows unless the SDK catalog exposes an exact parameter/variant or the SDK public API adds a Max Mode selector that the extension actually sends.
38
38
  - `@cursor/sdk` 1.0.13 adds latest-style `ModelListItem.aliases`. The extension registers only unambiguous aliases as pi model IDs (with the same context suffixes when applicable) and sends the alias back in `ModelSelection.id`, while sharing Cursor-only state such as fast defaults with the underlying catalog `id`. Aliases shared by multiple base models, such as generic family aliases, are skipped because the pi row metadata would otherwise imply one base model while Cursor may resolve the alias to another.
39
39
  - Session-scoped Cursor SDK agent pooling reuses one live `@cursor/sdk` agent across compatible follow-up turns within the same pi session scope. `computeCursorContextFingerprint()` and `shouldBootstrapCursorSend()` decide whether the next turn sends a full bootstrap prompt or an incremental follow-up. The pool recreates the agent when context diverges, when branch or compaction summaries appear after `/tree` navigation or compaction, when the API key identity changes, after send errors, on `session_shutdown`, and when `session_before_tree` / `session_tree` invalidate the active branch. Incremental sends omit the full Cursor SDK tool boundary block because the session agent retains prior bootstrap context.
40
+ - Pi steering/follow-up delivery can arrive while a split live Cursor SDK run is still active. The provider resolves pending live runs by scanning trailing `toolResult` messages while skipping trailing `user` messages, tracks the active live run per session scope, and resumes the in-flight run instead of calling `Agent.send()` again. When the context ends with steering user text after tool results, the provider releases the prior live run and chains an incremental `Agent.send()` for the latest user message in the same provider turn; if the prior run emits more text or tool requests after steering arrives, that stale activity is cancelled instead of surfacing another old-run tool turn and losing the new user input. A pre-send guard waits for or resumes any still-active scoped live run before starting a fresh send so `@cursor/sdk` `AgentBusyError` (`already has active run`) does not surface to pi users.
40
41
 
41
42
  ## Goal
42
43
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cursor-sdk",
3
- "version": "0.1.16",
3
+ "version": "0.1.17",
4
4
  "description": "pi provider extension backed by @cursor/sdk local agents",
5
5
  "author": "Mitch Fultz (https://github.com/fitchmultz)",
6
6
  "license": "MIT",
@@ -24,6 +24,9 @@
24
24
  "files": [
25
25
  "src",
26
26
  "scripts/refresh-cursor-model-snapshots.mjs",
27
+ "scripts/steering-rpc-smoke.mjs",
28
+ "scripts/tmux-live-smoke.sh",
29
+ "scripts/validate-smoke-jsonl.mjs",
27
30
  "README.md",
28
31
  "docs/cursor-model-ux-spec.md",
29
32
  "docs/cursor-live-smoke-checklist.md",
@@ -40,7 +43,10 @@
40
43
  "typecheck": "tsc --noEmit",
41
44
  "test": "vitest run",
42
45
  "test:watch": "vitest",
43
- "refresh:cursor-snapshots": "node scripts/refresh-cursor-model-snapshots.mjs"
46
+ "refresh:cursor-snapshots": "node scripts/refresh-cursor-model-snapshots.mjs",
47
+ "smoke:live": "scripts/tmux-live-smoke.sh",
48
+ "smoke:steering": "node scripts/steering-rpc-smoke.mjs",
49
+ "smoke:jsonl": "node scripts/validate-smoke-jsonl.mjs"
44
50
  },
45
51
  "dependencies": {
46
52
  "@cursor/sdk": "^1.0.13",
@@ -53,9 +59,9 @@
53
59
  "typebox": "*"
54
60
  },
55
61
  "devDependencies": {
56
- "@earendil-works/pi-ai": "^0.75.3",
57
- "@earendil-works/pi-coding-agent": "^0.75.3",
58
- "@earendil-works/pi-tui": "^0.75.3",
62
+ "@earendil-works/pi-ai": "^0.75.5",
63
+ "@earendil-works/pi-coding-agent": "^0.75.5",
64
+ "@earendil-works/pi-tui": "^0.75.5",
59
65
  "typebox": "^1.1.38",
60
66
  "typescript": "^6.0.3",
61
67
  "vitest": "^4.1.6"
@@ -0,0 +1,238 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * RPC steering smoke: queue steer after a native-replay tool-use turn completes execution.
4
+ */
5
+ import { spawn } from "node:child_process";
6
+ import { mkdirSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const root = fileURLToPath(new URL("..", import.meta.url));
11
+ const CHILD_SHUTDOWN_GRACE_MS = 2_000;
12
+
13
+ function printHelp() {
14
+ console.log(`RPC steering smoke for pi-cursor-sdk live runs.
15
+
16
+ Usage:
17
+ node scripts/steering-rpc-smoke.mjs
18
+
19
+ Environment:
20
+ SMOKE_SESSION_DIR Session directory for the RPC pi run. Defaults to /tmp/pi-cursor-steer-smoke-<timestamp>.
21
+ CURSOR_API_KEY Required Cursor API key for live pi runs.
22
+
23
+ Options:
24
+ -h, --help Show this help.
25
+
26
+ Exit codes:
27
+ 0 steering scenario completed without AgentBusyError; STEER_OK and STEER_CHAIN present
28
+ 1 validation failure, timeout, AgentBusyError, or non-zero pi exit
29
+
30
+ Notes:
31
+ - Runs pi in RPC mode with native tool replay enabled and the pi bridge disabled.
32
+ - Sends steer after the replayed bash tool finishes execution (post toolResult boundary).
33
+ - Prints a single JSON result line on success; errors go to stderr.`);
34
+ }
35
+
36
+ function fail(message) {
37
+ throw new Error(message);
38
+ }
39
+
40
+ function parseEvents(stdout) {
41
+ const events = [];
42
+ for (const line of stdout.split("\n")) {
43
+ if (!line.trim()) continue;
44
+ try {
45
+ events.push(JSON.parse(line));
46
+ } catch {
47
+ // ignore partial lines
48
+ }
49
+ }
50
+ return events;
51
+ }
52
+
53
+ function assistantText(events) {
54
+ return events
55
+ .filter((event) => event.type === "message_end" && event.message?.role === "assistant")
56
+ .map((event) =>
57
+ (event.message.content ?? [])
58
+ .filter((block) => block.type === "text")
59
+ .map((block) => block.text)
60
+ .join("\n"),
61
+ )
62
+ .join("\n");
63
+ }
64
+
65
+ function hasToolUseTurn(events) {
66
+ return events.some(
67
+ (event) =>
68
+ event.type === "message_end" &&
69
+ event.message?.role === "assistant" &&
70
+ event.message?.stopReason === "toolUse",
71
+ );
72
+ }
73
+
74
+ function hasToolExecutionEnd(events) {
75
+ return events.some((event) => event.type === "tool_execution_end");
76
+ }
77
+
78
+ function waitFor(getStdout, predicate, timeoutMs = 300_000) {
79
+ const start = Date.now();
80
+ return new Promise((resolve, reject) => {
81
+ const tick = () => {
82
+ const events = parseEvents(getStdout());
83
+ if (predicate(events)) {
84
+ resolve(events);
85
+ return;
86
+ }
87
+ if (Date.now() - start > timeoutMs) {
88
+ reject(
89
+ new Error(
90
+ `timeout after ${timeoutMs}ms\nassistantText=${assistantText(events)}\nstdoutTail=${getStdout().slice(-4000)}`,
91
+ ),
92
+ );
93
+ return;
94
+ }
95
+ setTimeout(tick, 500);
96
+ };
97
+ tick();
98
+ });
99
+ }
100
+
101
+ function waitForChildClose(child) {
102
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(child.exitCode ?? 1);
103
+ return new Promise((resolve) => {
104
+ child.once("close", (code) => resolve(code ?? 1));
105
+ });
106
+ }
107
+
108
+ function signalChild(child, signal) {
109
+ if (!child.pid) return;
110
+ try {
111
+ if (process.platform === "win32") {
112
+ child.kill(signal);
113
+ } else {
114
+ process.kill(-child.pid, signal);
115
+ }
116
+ } catch {
117
+ try {
118
+ child.kill(signal);
119
+ } catch {
120
+ // child already exited
121
+ }
122
+ }
123
+ }
124
+
125
+ async function terminateChild(child) {
126
+ child.stdin.destroy();
127
+ if (child.exitCode !== null || child.signalCode !== null) return;
128
+ signalChild(child, "SIGTERM");
129
+ const killTimer = setTimeout(() => signalChild(child, "SIGKILL"), CHILD_SHUTDOWN_GRACE_MS);
130
+ try {
131
+ await waitForChildClose(child);
132
+ } finally {
133
+ clearTimeout(killTimer);
134
+ }
135
+ }
136
+
137
+ async function runPiRpcSmoke(sessionDir) {
138
+ const args = ["-e", root, "--cursor-no-fast", "--model", "cursor/composer-2.5", "--mode", "rpc", "--session-dir", sessionDir];
139
+ const env = {
140
+ ...process.env,
141
+ PI_CURSOR_SETTING_SOURCES: "none",
142
+ PI_CURSOR_NATIVE_TOOL_DISPLAY: "1",
143
+ PI_CURSOR_PI_TOOL_BRIDGE: "0",
144
+ };
145
+
146
+ const child = spawn("pi", args, { cwd: root, env, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32" });
147
+ let closed = false;
148
+ let stdout = "";
149
+ let stderr = "";
150
+ child.stdout.on("data", (chunk) => {
151
+ stdout += chunk.toString();
152
+ });
153
+ child.stderr.on("data", (chunk) => {
154
+ stderr += chunk.toString();
155
+ });
156
+
157
+ const send = (obj) => {
158
+ if (!child.stdin.writable) fail("pi stdin closed before smoke command could be sent");
159
+ child.stdin.write(`${JSON.stringify(obj)}\n`);
160
+ };
161
+
162
+ try {
163
+ send({
164
+ type: "prompt",
165
+ message:
166
+ "Steering smoke. Use bash once to run: git status --short. Do not answer until after the tool completes. Final answer must include STEER_OK=yes.",
167
+ });
168
+
169
+ await waitFor(
170
+ () => stdout,
171
+ (events) => hasToolUseTurn(events),
172
+ );
173
+
174
+ await waitFor(
175
+ () => stdout,
176
+ (events) => hasToolExecutionEnd(events),
177
+ );
178
+
179
+ send({ type: "steer", message: "and also include STEER_CHAIN=ok in the final answer" });
180
+
181
+ await waitFor(
182
+ () => stdout,
183
+ (events) => {
184
+ const text = assistantText(events);
185
+ return text.includes("STEER_OK=yes") && text.includes("STEER_CHAIN=ok") && events.some((event) => event.type === "agent_end");
186
+ },
187
+ );
188
+
189
+ const combined = stdout + stderr;
190
+ if (/already has active run|AgentBusyError/i.test(combined)) {
191
+ fail("AgentBusyError detected in smoke output");
192
+ }
193
+
194
+ const text = assistantText(parseEvents(stdout));
195
+ if (!text.includes("STEER_OK=yes")) {
196
+ fail(`missing STEER_OK=yes in assistant output: ${text.slice(0, 500)}`);
197
+ }
198
+ if (!text.includes("STEER_CHAIN=ok")) {
199
+ fail(`missing STEER_CHAIN=ok in assistant output: ${text.slice(0, 500)}`);
200
+ }
201
+
202
+ child.stdin.end();
203
+ const exitCode = await waitForChildClose(child);
204
+ closed = true;
205
+ if (exitCode !== 0) {
206
+ fail(`pi exited ${exitCode}\nstderr=${stderr.slice(-2000)}`);
207
+ }
208
+
209
+ return {
210
+ ok: true,
211
+ sessionDir,
212
+ steerOk: true,
213
+ steerChain: true,
214
+ };
215
+ } finally {
216
+ if (!closed) await terminateChild(child);
217
+ }
218
+ }
219
+
220
+ async function main() {
221
+ if (process.argv.includes("-h") || process.argv.includes("--help")) {
222
+ printHelp();
223
+ return;
224
+ }
225
+
226
+ if (!process.env.CURSOR_API_KEY) {
227
+ fail("steering-rpc-smoke: CURSOR_API_KEY is required");
228
+ }
229
+
230
+ const sessionDir = process.env.SMOKE_SESSION_DIR ?? join("/tmp", `pi-cursor-steer-smoke-${Date.now()}`);
231
+ mkdirSync(sessionDir, { recursive: true });
232
+ console.log(JSON.stringify(await runPiRpcSmoke(sessionDir)));
233
+ }
234
+
235
+ main().catch((error) => {
236
+ console.error(error instanceof Error ? error.message : String(error));
237
+ process.exitCode = 1;
238
+ });