@emmaneugene/pi-cursor-sdk 0.4.0 → 0.4.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +2 -0
  3. package/dist/cursor-extension-factory-guard.js +31 -0
  4. package/dist/cursor-pi-tool-bridge-server.js +3 -0
  5. package/dist/cursor-pi-tool-bridge.js +28 -7
  6. package/dist/cursor-provider-lazy.js +2 -2
  7. package/dist/cursor-provider-live-run-drain.js +4 -4
  8. package/dist/cursor-provider-run-finalizer.js +1 -0
  9. package/dist/cursor-provider-runtime-context.js +1 -0
  10. package/dist/cursor-provider-turn-prepare.js +17 -9
  11. package/dist/cursor-provider-turn-runner.js +5 -4
  12. package/dist/cursor-provider.js +3 -2
  13. package/dist/cursor-session-agent.js +9 -7
  14. package/dist/index.js +108 -53
  15. package/docs/cursor-live-smoke-checklist.md +1 -1
  16. package/docs/cursor-model-ux-spec.md +1 -1
  17. package/docs/cursor-native-tool-visual-audit.md +3 -3
  18. package/docs/cursor-testing-lessons.md +24 -0
  19. package/docs/platform-smoke.md +1 -1
  20. package/node_modules/cross-spawn/node_modules/which/CHANGELOG.md +166 -0
  21. package/package.json +1 -1
  22. package/scripts/lib/cursor-visual-render.mjs +12 -2
  23. package/scripts/visual-tui-smoke-self-test.mjs +9 -33
  24. package/scripts/visual-tui-smoke.mjs +54 -11
  25. package/src/cursor-extension-factory-guard.ts +57 -0
  26. package/src/cursor-pi-tool-bridge-server.ts +4 -0
  27. package/src/cursor-pi-tool-bridge.ts +33 -7
  28. package/src/cursor-provider-lazy.ts +3 -1
  29. package/src/cursor-provider-live-run-drain.ts +4 -3
  30. package/src/cursor-provider-run-finalizer.ts +1 -0
  31. package/src/cursor-provider-runtime-context.ts +13 -0
  32. package/src/cursor-provider-turn-prepare.ts +20 -9
  33. package/src/cursor-provider-turn-runner.ts +13 -4
  34. package/src/cursor-provider-turn-types.ts +2 -0
  35. package/src/cursor-provider.ts +4 -1
  36. package/src/cursor-session-agent.ts +11 -7
  37. package/src/index.ts +124 -52
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.2 - 2026-09-07
4
+
5
+ ### Fixed
6
+
7
+ - Register an isolated Cursor provider, SDK agent scope, and pi tool bridge for nested in-process child sessions. A non-Cursor parent can now dispatch a pi subagent with a Cursor model, and a Cursor parent can dispatch a Cursor-model pi subagent without waiting on or disposing its own busy Cursor SDK agent.
8
+
9
+ ## 0.4.1 - 2026-09-07
10
+
11
+ ### Fixed
12
+
13
+ - Keep the first in-process factory as the Cursor owner. A pi child session that calls `createAgentSession` + `bindExtensions` no longer re-runs the factory in a way that disposes the live parent bridge (`Cursor pi tool bridge extension reloaded`), steals session scope, or aborts the parent `pi__subagent` call.
14
+
3
15
  ## 0.4.0 - 2026-09-06
4
16
 
5
17
  Breaking: Cursor Cloud support is removed. Cursor SDK runs are local-only.
package/README.md CHANGED
@@ -367,6 +367,8 @@ Local Cursor runs use two separate tool surfaces:
367
367
 
368
368
  Bridge capabilities are snapshotted from `pi.getActiveTools()` and `pi.getAllTools()` for each Cursor run, including per-tool prompt guidelines when pi exposes them. Cursor sees active bridgeable pi tools as collision-safe MCP names such as `pi__sem_reindex` only when they are exposed in that current run. When exposed, Cursor is instructed to prefer `pi__mcp` for MCP work and `pi__subagent` for delegation; Cursor-configured MCP and Cursor-native subagents are fallbacks when the matching pi tool is not exposed or is unavailable. Pi session output, tool cards, confirmations, hooks, renderers, history, and abort behavior use the real pi tool name, such as `sem_reindex`. The bridge queues Cursor's MCP call, emits a normal pi `toolCall`, waits for the matching pi `toolResult`, and resolves that result back into the same live Cursor SDK run without creating a new `Agent`, unless the run was disposed, aborted, or cancelled. The bridge does not call pi tool `execute()` handlers directly.
369
369
 
370
+ Pi subagents can select Cursor models under both Cursor and non-Cursor parents. Each nested Cursor child registers a child-local provider and bridge and uses an isolated SDK agent scope, so it does not replace or wait on the parent's active Cursor agent.
371
+
370
372
  Overlapping built-in pi tools (`read`, `bash`, `write`, `edit`, `grep`, `find`, `ls`) are hidden by default because Cursor local agents already have native equivalents. Extension/custom tools and non-overlapping active tools present in pi's active tool registry normally remain exposed. The bridge also exposes `cursor_ask_question` as `pi__cursor_ask_question` when enabled, allowing Cursor to ask the user through pi UI instead of silently choosing a default. When pi has visible Agent Skills loaded, the extension rewrites pi's skill catalog for Cursor and exposes `cursor_activate_skill` as `pi__cursor_activate_skill`; Cursor should call that bridge tool with a listed skill name to load the full `SKILL.md` and bundled resource list before applying the skill. If the bridge is disabled, the catalog remains available and instructs Cursor to fall back to reading the listed `SKILL.md` path directly.
371
373
 
372
374
  Cursor-native tool replay is separate from the bridge. Replay cards are display-only recorded Cursor SDK activity. They never re-run Cursor-side commands, reapply Cursor edits, call MCP servers, or mutate pi state. See [Cursor native tool replay](docs/cursor-native-tool-replay.md).
@@ -0,0 +1,31 @@
1
+ let factoryOwnerToken;
2
+ export function claimCursorExtensionFactory() {
3
+ if (factoryOwnerToken)
4
+ return { kind: "nested" };
5
+ const token = Symbol("cursor-extension-factory-owner");
6
+ factoryOwnerToken = token;
7
+ return { kind: "owner", token };
8
+ }
9
+ export function releaseCursorExtensionFactory(token) {
10
+ if (factoryOwnerToken === token) {
11
+ factoryOwnerToken = undefined;
12
+ }
13
+ }
14
+ /**
15
+ * Install the owner's release handler after all other factory registration
16
+ * succeeds. The final handler keeps ownership until earlier shutdown cleanup
17
+ * has finished.
18
+ */
19
+ export function registerCursorExtensionFactoryRelease(pi, claim) {
20
+ pi.on("session_shutdown", () => {
21
+ releaseCursorExtensionFactory(claim.token);
22
+ });
23
+ }
24
+ export const __testUtils = {
25
+ isInstalled() {
26
+ return factoryOwnerToken !== undefined;
27
+ },
28
+ reset() {
29
+ factoryOwnerToken = undefined;
30
+ },
31
+ };
@@ -41,6 +41,9 @@ export class CursorPiToolBridgeRegistry {
41
41
  run.emitStartDiagnostics(bridgeEnabled);
42
42
  return run;
43
43
  }
44
+ hasLiveRuns() {
45
+ return this.runs.size > 0;
46
+ }
44
47
  async disposeAll(reason = "Cursor pi tool bridge disposed") {
45
48
  await Promise.all([...this.runs].map(async (run) => {
46
49
  run.cancel(reason);
@@ -48,13 +48,9 @@ Get-CimInstance Win32_Process -Filter "Name = 'bash.exe' OR Name = 'sh.exe'" |
48
48
  windowsHide: true,
49
49
  });
50
50
  }
51
- export function registerCursorPiToolBridge(pi) {
52
- bridgeToolExecutionAbortTracker.abortAll("Cursor pi tool bridge extension reloaded");
53
- void registeredCursorPiToolBridge?.disposeAll("Cursor pi tool bridge extension reloaded");
54
- const bridge = new CursorPiToolBridgeRegistry(pi);
55
- registeredCursorPiToolBridge = bridge;
51
+ function attachCursorPiToolBridgeHandlers(pi, bridge, options) {
56
52
  pi.on("tool_call", (event, ctx) => {
57
- if (registeredCursorPiToolBridge !== bridge)
53
+ if (!options.isActive())
58
54
  return undefined;
59
55
  if (!bridge.hasPendingPiToolCallId(event.toolCallId)) {
60
56
  return isCursorPiBridgeToolCallId(event.toolCallId)
@@ -81,9 +77,34 @@ export function registerCursorPiToolBridge(pi) {
81
77
  });
82
78
  pi.on("session_shutdown", async (event) => {
83
79
  const reason = `Cursor pi tool bridge session shutdown: ${event.reason}`;
84
- bridgeToolExecutionAbortTracker.abortAll(reason);
80
+ if (options.abortAllOnShutdown)
81
+ bridgeToolExecutionAbortTracker.abortAll(reason);
85
82
  await bridge.disposeAll(reason);
86
83
  });
84
+ }
85
+ export function registerCursorPiToolBridge(pi) {
86
+ // Replacing a bridge during a live MCP run cancels its pending pi tool
87
+ // calls. Keep the active registry as a final safety belt.
88
+ if (registeredCursorPiToolBridge?.hasLiveRuns()) {
89
+ return registeredCursorPiToolBridge;
90
+ }
91
+ bridgeToolExecutionAbortTracker.abortAll("Cursor pi tool bridge extension reloaded");
92
+ void registeredCursorPiToolBridge?.disposeAll("Cursor pi tool bridge extension reloaded");
93
+ const bridge = new CursorPiToolBridgeRegistry(pi);
94
+ registeredCursorPiToolBridge = bridge;
95
+ attachCursorPiToolBridgeHandlers(pi, bridge, {
96
+ abortAllOnShutdown: true,
97
+ isActive: () => registeredCursorPiToolBridge === bridge,
98
+ });
99
+ return bridge;
100
+ }
101
+ /** Register a bridge owned only by one nested in-process child session. */
102
+ export function registerNestedCursorPiToolBridge(pi) {
103
+ const bridge = new CursorPiToolBridgeRegistry(pi);
104
+ attachCursorPiToolBridgeHandlers(pi, bridge, {
105
+ abortAllOnShutdown: false,
106
+ isActive: () => true,
107
+ });
87
108
  return bridge;
88
109
  }
89
110
  export function getRegisteredCursorPiToolBridge() {
@@ -21,11 +21,11 @@ function makeProviderRuntimeErrorMessage(model, error, apiKey) {
21
21
  errorMessage: `Cursor provider runtime failed: ${sanitizeCursorProviderError(error, apiKey)}`,
22
22
  };
23
23
  }
24
- export function streamCursorLazy(model, context, options) {
24
+ export function streamCursorLazy(model, context, options, runtimeContext) {
25
25
  const outer = createAssistantMessageEventStream();
26
26
  queueMicrotask(async () => {
27
27
  try {
28
- for await (const event of streamCursor(model, context, options)) {
28
+ for await (const event of streamCursor(model, context, options, runtimeContext)) {
29
29
  outer.push(event);
30
30
  }
31
31
  }
@@ -32,8 +32,8 @@ function getCursorNativeReplayIdFromToolCallId(toolCallId) {
32
32
  export function getPendingCursorLiveRun(context) {
33
33
  return cursorLiveRuns.getPendingFromContext(context, getCursorNativeReplayIdFromToolCallId);
34
34
  }
35
- export function getActiveCursorLiveRunForCurrentScope() {
36
- return cursorLiveRuns.getActiveForScope();
35
+ export function getActiveCursorLiveRunForScope(scopeKey) {
36
+ return cursorLiveRuns.getActiveForScope(scopeKey);
37
37
  }
38
38
  function splitTextIntoReplayDeltas(text) {
39
39
  const deltas = [];
@@ -334,10 +334,10 @@ export async function drainCursorLiveRunTurn(stream, partial, model, context, ru
334
334
  });
335
335
  }
336
336
  }
337
- export async function drainExistingCursorLiveRunBeforeSend(stream, partial, model, context, signal, turnDebugRecorder) {
337
+ export async function drainExistingCursorLiveRunBeforeSend(stream, partial, model, context, signal, turnDebugRecorder, scopeKey) {
338
338
  turnDebugRecorder?.recordDrainEvent("pre_send_start", {});
339
339
  while (true) {
340
- const run = getPendingCursorLiveRun(context) ?? getActiveCursorLiveRunForCurrentScope();
340
+ const run = getPendingCursorLiveRun(context) ?? getActiveCursorLiveRunForScope(scopeKey);
341
341
  if (!run || run.disposed) {
342
342
  turnDebugRecorder?.recordDrainEvent("pre_send_end", { outcome: "continue_send", reason: "no_pending_run" });
343
343
  return "continue_send";
@@ -89,6 +89,7 @@ export class CursorRunFinalizer {
89
89
  if (liveCompletion) {
90
90
  void liveCompletion.waitCompletion
91
91
  .finally(async () => {
92
+ await prepared?.lifecycle.dispose().catch(() => { });
92
93
  await this.finalizeSdkEventDebugBestEffort();
93
94
  this.safeCleanup(() => this.params.sdkProcessErrorGuard.dispose());
94
95
  })
@@ -0,0 +1 @@
1
+ export {};
@@ -20,20 +20,23 @@ import { MISSING_CURSOR_API_KEY_MESSAGE } from "./cursor-provider-errors.js";
20
20
  import { CursorSdkTurnCoordinator } from "./cursor-provider-turn-coordinator.js";
21
21
  import { resolveCursorApiKey } from "./cursor-api-key.js";
22
22
  import { loadCursorSdk } from "./cursor-sdk-runtime.js";
23
- export function resolveCursorProviderTurnConfig(cwd) {
24
- return resolveEffectiveCursorConfig({ cwd, projectTrusted: getCursorSessionProjectTrusted() });
23
+ export function resolveCursorProviderTurnConfig(cwd, projectTrusted = getCursorSessionProjectTrusted()) {
24
+ return resolveEffectiveCursorConfig({ cwd, projectTrusted });
25
25
  }
26
- function buildLocalCursorProviderTurnLifecycle(lease, scopeKey) {
26
+ function buildLocalCursorProviderTurnLifecycle(lease, scopeKey, disposeAgentAfterTurn) {
27
27
  return {
28
28
  trackRunCompletion: (completion) => lease.trackRunCompletion(completion),
29
29
  commitSend: (context, bootstrapped) => lease.commitSend(context, bootstrapped),
30
30
  abandon: () => abandonSessionCursorAgent(scopeKey),
31
- dispose: async () => { },
31
+ dispose: async () => {
32
+ if (disposeAgentAfterTurn)
33
+ await resetSessionCursorAgent(scopeKey);
34
+ },
32
35
  };
33
36
  }
34
37
  async function prepareCursorLocalProviderTurn(prepareParams) {
35
38
  const { params, cwd, resolvedApiKey, sdkEventDebug, throwIfAborted, resolvedConfig, agentMode, selection, fastEnabled } = prepareParams;
36
- const { model, context, options } = params;
39
+ const { model, context, options, runtimeContext } = params;
37
40
  let restoreCursorSdkOutputFilter;
38
41
  let sessionAgentScopeKey;
39
42
  let liveRun;
@@ -54,6 +57,7 @@ async function prepareCursorLocalProviderTurn(prepareParams) {
54
57
  const queuedBridgeRequestsBeforeLiveRun = [];
55
58
  let liveRunForBridgeQueue;
56
59
  const bridgeExcludeToolNames = buildCursorBridgeExcludeToolNames(resolvedConfig);
60
+ const localResumeEnabled = runtimeContext?.localResume ?? resolvedConfig.local.resume.value;
57
61
  const sessionAgentAcquireParams = {
58
62
  apiKey: resolvedApiKey,
59
63
  agentMode,
@@ -61,8 +65,12 @@ async function prepareCursorLocalProviderTurn(prepareParams) {
61
65
  modelSelection: selection,
62
66
  settingSources,
63
67
  localSafety,
64
- localResume: resolvedConfig.local.resume.value,
68
+ localResume: localResumeEnabled,
65
69
  useHttp1ForAgent,
70
+ runtimeScope: runtimeContext
71
+ ? { scopeKey: runtimeContext.scopeKey, sessionFile: runtimeContext.sessionFile }
72
+ : undefined,
73
+ bridge: runtimeContext?.bridge,
66
74
  bridgeExcludeToolNames,
67
75
  debugRecorder: sdkEventDebug,
68
76
  onBridgeToolRequest: (request) => {
@@ -124,7 +132,7 @@ async function prepareCursorLocalProviderTurn(prepareParams) {
124
132
  };
125
133
  const sessionBridgeRun = bridgeRun;
126
134
  const promptInputTokens = estimateCursorPromptTokens(prompt, promptOptions);
127
- const useNativeToolReplay = isCursorNativeToolDisplayRuntimeEnabled();
135
+ const useNativeToolReplay = runtimeContext?.nativeToolReplay ?? isCursorNativeToolDisplayRuntimeEnabled();
128
136
  const activeToolNames = getActiveContextToolNames(context);
129
137
  sdkEventDebug?.recordProviderMeta({
130
138
  model: {
@@ -142,7 +150,7 @@ async function prepareCursorLocalProviderTurn(prepareParams) {
142
150
  toolManifestEnabled: resolveCursorToolManifestEnabled(),
143
151
  agentMode,
144
152
  localForce: resolvedConfig.local.force.value,
145
- localResume: resolvedConfig.local.resume.value,
153
+ localResume: localResumeEnabled,
146
154
  resumedAgent: sessionAgentLease.resumed,
147
155
  activeToolNames: activeToolNames ? [...activeToolNames] : [],
148
156
  sessionAgentScopeKey,
@@ -204,7 +212,7 @@ async function prepareCursorLocalProviderTurn(prepareParams) {
204
212
  sessionAgentLease,
205
213
  localForce: resolvedConfig.local.force,
206
214
  restoreCursorSdkOutputFilter,
207
- lifecycle: buildLocalCursorProviderTurnLifecycle(sessionAgentLease, sessionAgentScopeKey),
215
+ lifecycle: buildLocalCursorProviderTurnLifecycle(sessionAgentLease, sessionAgentScopeKey, runtimeContext?.disposeAgentAfterTurn === true),
208
216
  runtime: liveRun
209
217
  ? { kind: "live", liveRun, turnCoordinator }
210
218
  : { kind: "direct", turnCoordinator },
@@ -42,7 +42,8 @@ export class CursorProviderTurnRunner {
42
42
  });
43
43
  try {
44
44
  this.throwIfAborted();
45
- const cwd = getCursorSessionCwd();
45
+ const runtimeContext = this.params.runtimeContext;
46
+ const cwd = runtimeContext?.cwd ?? getCursorSessionCwd();
46
47
  this.sdkEventDebug = CursorSdkEventDebugSink.maybeCreate({
47
48
  cwd,
48
49
  modelId: model.id,
@@ -50,10 +51,10 @@ export class CursorProviderTurnRunner {
50
51
  });
51
52
  sdkEventDebugRef.current = this.sdkEventDebug;
52
53
  this.sdkEventDebug?.recordContextSnapshot(context);
53
- const resolvedConfig = resolveCursorProviderTurnConfig(cwd);
54
- const localScopeKey = getCursorSessionScopeKey();
54
+ const resolvedConfig = resolveCursorProviderTurnConfig(cwd, runtimeContext?.projectTrusted);
55
+ const localScopeKey = runtimeContext?.scopeKey ?? getCursorSessionScopeKey();
55
56
  sdkProcessErrorGuard.containLocalTransportClosedPipe(() => invalidateSessionAgent(localScopeKey, { deadTransport: true }));
56
- if ((await drainExistingCursorLiveRunBeforeSend(stream, partial, model, context, options?.signal, this.sdkEventDebug)) ===
57
+ if ((await drainExistingCursorLiveRunBeforeSend(stream, partial, model, context, options?.signal, this.sdkEventDebug, localScopeKey)) ===
57
58
  "stream_ended") {
58
59
  return;
59
60
  }
@@ -27,7 +27,7 @@ function makeInitialMessage(model) {
27
27
  timestamp: Date.now(),
28
28
  };
29
29
  }
30
- export function streamCursor(model, context, options) {
30
+ export function streamCursor(model, context, options, runtimeContext) {
31
31
  const stream = createAssistantMessageEventStream();
32
32
  const sdkEventDebugRef = {};
33
33
  attachCursorSdkEventDebugPiStreamTap(stream, sdkEventDebugRef);
@@ -39,11 +39,12 @@ export function streamCursor(model, context, options) {
39
39
  stream,
40
40
  partial,
41
41
  options,
42
+ runtimeContext,
42
43
  sdkEventDebugRef,
43
44
  });
44
45
  try {
45
46
  stream.push({ type: "start", partial });
46
- await runExclusiveCursorSessionTurn(getCursorSessionScopeKey(), () => runner.run(installCursorSdkProcessErrorGuard()), options?.signal);
47
+ await runExclusiveCursorSessionTurn(runtimeContext?.scopeKey ?? getCursorSessionScopeKey(), () => runner.run(installCursorSdkProcessErrorGuard()), options?.signal);
47
48
  }
48
49
  catch (error) {
49
50
  await runner.handleOuterCatch(error);
@@ -283,16 +283,18 @@ async function createSessionAgentEntry(scopeKey, persistentStore, instanceId, se
283
283
  let bridgeRun;
284
284
  let sessionStore;
285
285
  try {
286
- const registeredBridge = getRegisteredCursorPiToolBridge();
286
+ const registeredBridge = params.bridge ?? getRegisteredCursorPiToolBridge();
287
287
  if (registeredBridge) {
288
- bridgeRun = await registeredBridge.createRun({
288
+ const createdBridgeRun = await registeredBridge.createRun({
289
289
  onToolRequest: params.onBridgeToolRequest,
290
290
  debugRecorder: params.debugRecorder,
291
291
  excludeToolNames: params.bridgeExcludeToolNames,
292
292
  });
293
- if (!bridgeRun.enabled || !bridgeRun.mcpServers) {
294
- await bridgeRun.dispose();
295
- bridgeRun = undefined;
293
+ if (!createdBridgeRun.enabled || !createdBridgeRun.mcpServers) {
294
+ await createdBridgeRun.dispose();
295
+ }
296
+ else {
297
+ bridgeRun = createdBridgeRun;
296
298
  }
297
299
  }
298
300
  const resolvedPoolKey = buildSessionAgentPoolKey(scopeKey, params);
@@ -382,8 +384,8 @@ export function invalidateSessionAgent(scopeKey = getCursorSessionScopeKey(), op
382
384
  deadTransportScopeKeys.add(scopeKey);
383
385
  }
384
386
  export async function acquireSessionCursorAgent(params) {
385
- const scopeKey = getCursorSessionScopeKey();
386
- const persistentStore = getCursorSessionFile() !== undefined;
387
+ const scopeKey = params.runtimeScope?.scopeKey ?? getCursorSessionScopeKey();
388
+ const persistentStore = params.runtimeScope ? params.runtimeScope.sessionFile !== undefined : getCursorSessionFile() !== undefined;
387
389
  let forceCreate = params.forceCreate === true;
388
390
  while (true) {
389
391
  assertScopeAcceptsAcquire(scopeKey);
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { discoverModels } from "./model-discovery.js";
2
3
  import { registerCursorRuntimeControls } from "./cursor-state.js";
3
4
  import { registerCursorNativeToolDisplay } from "./cursor-native-tool-display-registration.js";
4
- import { registerCursorPiToolBridge } from "./cursor-pi-tool-bridge.js";
5
+ import { registerCursorPiToolBridge, registerNestedCursorPiToolBridge } from "./cursor-pi-tool-bridge.js";
5
6
  import { registerCursorQuestionTool } from "./cursor-question-tool.js";
6
7
  import { registerCursorSkillTool } from "./cursor-skill-tool.js";
7
8
  import { registerCursorSessionScope } from "./cursor-session-scope.js";
@@ -15,68 +16,122 @@ import { registerCursorAgentsContextDedup } from "./cursor-agents-context-regist
15
16
  import { registerCursorOverflowNormalization } from "./cursor-provider-overflow.js";
16
17
  import { registerCursorSdkSessionProcessErrorGuard } from "./cursor-sdk-process-error-guard.js";
17
18
  import { prepareCursorSessionForCompaction } from "./cursor-session-compaction-prep.js";
18
- function createCursorProviderConfig(models) {
19
+ import { disposeSessionCursorAgent } from "./cursor-session-agent.js";
20
+ import { getCursorSessionCwd, getCursorSessionProjectTrusted } from "./cursor-session-scope.js";
21
+ import { claimCursorExtensionFactory, registerCursorExtensionFactoryRelease, releaseCursorExtensionFactory, } from "./cursor-extension-factory-guard.js";
22
+ let activeCursorProviderModels;
23
+ function createCursorProviderConfig(models, streamSimple = streamCursorLazy) {
19
24
  return {
20
25
  name: "Cursor",
21
26
  baseUrl: "https://cursor.com",
22
27
  apiKey: CURSOR_API_KEY_CONFIG_VALUE,
23
28
  api: "cursor-sdk",
24
29
  models,
25
- streamSimple: streamCursorLazy,
30
+ streamSimple,
26
31
  };
27
32
  }
28
- function registerCursorProvider(pi, models) {
29
- pi.registerProvider("cursor", createCursorProviderConfig(models));
33
+ function registerCursorProvider(pi, models, streamSimple) {
34
+ pi.registerProvider("cursor", createCursorProviderConfig(models, streamSimple));
30
35
  }
31
- export default async function (pi) {
32
- // Session cwd must register before other session_start listeners that depend on it.
33
- registerCursorSessionScope(pi);
34
- registerCursorSessionAgentLineage(pi);
35
- registerCursorSessionAgentLifecycle(pi);
36
- registerCursorSessionAgentResume(pi);
37
- pi.on("session_before_compact", async () => {
38
- await prepareCursorSessionForCompaction();
36
+ function registerNestedCursorProvider(pi, models) {
37
+ const bridge = registerNestedCursorPiToolBridge(pi);
38
+ const nestedRuntimeId = randomUUID();
39
+ let runtimeContext = {
40
+ scopeKey: `__nested_cursor__:${nestedRuntimeId}`,
41
+ cwd: getCursorSessionCwd(),
42
+ sessionFile: undefined,
43
+ projectTrusted: getCursorSessionProjectTrusted(),
44
+ bridge,
45
+ localResume: false,
46
+ nativeToolReplay: false,
47
+ disposeAgentAfterTurn: true,
48
+ };
49
+ pi.on("session_start", (_event, ctx) => {
50
+ const sessionFile = ctx.sessionManager?.getSessionFile?.() ?? undefined;
51
+ const sessionId = ctx.sessionManager?.getSessionId?.() ?? nestedRuntimeId;
52
+ runtimeContext = {
53
+ ...runtimeContext,
54
+ scopeKey: sessionFile ?? `__nested_cursor__:${sessionId}`,
55
+ cwd: ctx.cwd,
56
+ sessionFile,
57
+ projectTrusted: ctx.isProjectTrusted?.() === true || runtimeContext.projectTrusted,
58
+ };
39
59
  });
40
- registerCursorRuntimeControls(pi);
41
- registerCursorNativeToolDisplay(pi);
42
- registerCursorQuestionTool(pi);
43
- registerCursorSkillTool(pi);
44
- registerCursorPiToolBridge(pi);
45
- registerCursorAgentsContextDedup(pi);
46
- registerCursorOverflowNormalization(pi);
47
- let fallbackIssue;
48
- const models = await discoverModels({
49
- onFallback: (issue) => {
50
- fallbackIssue = issue;
51
- },
60
+ pi.on("session_shutdown", async () => {
61
+ await disposeSessionCursorAgent(runtimeContext.scopeKey);
52
62
  });
53
- if (fallbackIssue) {
54
- registerCursorFallbackIssueWarning(pi, fallbackIssue);
63
+ registerCursorProvider(pi, models, (model, context, options) => streamCursorLazy(model, context, options, runtimeContext));
64
+ }
65
+ export default async function (pi) {
66
+ const factoryClaim = claimCursorExtensionFactory();
67
+ if (factoryClaim.kind === "nested") {
68
+ if (!activeCursorProviderModels) {
69
+ throw new Error("Nested Cursor provider loaded before the owner model catalog was ready");
70
+ }
71
+ registerNestedCursorProvider(pi, activeCursorProviderModels);
72
+ return;
73
+ }
74
+ try {
75
+ // Discover first. A discovery failure must not leave process-global
76
+ // registrars from a discarded extension load.
77
+ let fallbackIssue;
78
+ const models = await discoverModels({
79
+ onFallback: (issue) => {
80
+ fallbackIssue = issue;
81
+ },
82
+ });
83
+ activeCursorProviderModels = models;
84
+ // Session cwd must register before other session_start listeners that depend on it.
85
+ registerCursorSessionScope(pi);
86
+ registerCursorSessionAgentLineage(pi);
87
+ registerCursorSessionAgentLifecycle(pi);
88
+ registerCursorSessionAgentResume(pi);
89
+ pi.on("session_before_compact", async () => {
90
+ await prepareCursorSessionForCompaction();
91
+ });
92
+ registerCursorRuntimeControls(pi);
93
+ registerCursorNativeToolDisplay(pi);
94
+ registerCursorQuestionTool(pi);
95
+ registerCursorSkillTool(pi);
96
+ registerCursorPiToolBridge(pi);
97
+ registerCursorAgentsContextDedup(pi);
98
+ registerCursorOverflowNormalization(pi);
99
+ if (fallbackIssue) {
100
+ registerCursorFallbackIssueWarning(pi, fallbackIssue);
101
+ }
102
+ pi.registerCommand("cursor-refresh-models", {
103
+ description: "Refresh the live Cursor model catalog without restarting pi",
104
+ handler: async (_args, ctx) => {
105
+ let refreshFallbackIssue;
106
+ const apiKey = resolveCursorApiKey(await ctx.modelRegistry.getApiKeyForProvider("cursor"));
107
+ const refreshedModels = await discoverModels({
108
+ apiKey,
109
+ forceRefresh: true,
110
+ onFallback: (issue) => {
111
+ refreshFallbackIssue = issue;
112
+ },
113
+ });
114
+ registerCursorProvider(pi, refreshedModels);
115
+ if (!ctx.hasUI)
116
+ return;
117
+ if (refreshFallbackIssue) {
118
+ ctx.ui.notify(`Cursor model catalog refresh did not use a live catalog: ${refreshFallbackIssue.message}`, "warning");
119
+ }
120
+ else {
121
+ ctx.ui.notify(`Cursor model catalog refreshed with ${refreshedModels.length} model${refreshedModels.length === 1 ? "" : "s"}.`, "info");
122
+ }
123
+ },
124
+ });
125
+ registerCursorProvider(pi, models);
126
+ // Keep the process error guard near the end so earlier Cursor cleanup
127
+ // remains protected during session shutdown.
128
+ registerCursorSdkSessionProcessErrorGuard(pi);
129
+ // Register last so ownership remains protected until all other Cursor
130
+ // session_shutdown handlers finish.
131
+ registerCursorExtensionFactoryRelease(pi, factoryClaim);
132
+ }
133
+ catch (error) {
134
+ releaseCursorExtensionFactory(factoryClaim.token);
135
+ throw error;
55
136
  }
56
- pi.registerCommand("cursor-refresh-models", {
57
- description: "Refresh the live Cursor model catalog without restarting pi",
58
- handler: async (_args, ctx) => {
59
- let refreshFallbackIssue;
60
- const apiKey = resolveCursorApiKey(await ctx.modelRegistry.getApiKeyForProvider("cursor"));
61
- const refreshedModels = await discoverModels({
62
- apiKey,
63
- forceRefresh: true,
64
- onFallback: (issue) => {
65
- refreshFallbackIssue = issue;
66
- },
67
- });
68
- registerCursorProvider(pi, refreshedModels);
69
- if (!ctx.hasUI)
70
- return;
71
- if (refreshFallbackIssue) {
72
- ctx.ui.notify(`Cursor model catalog refresh did not use a live catalog: ${refreshFallbackIssue.message}`, "warning");
73
- }
74
- else {
75
- ctx.ui.notify(`Cursor model catalog refreshed with ${refreshedModels.length} model${refreshedModels.length === 1 ? "" : "s"}.`, "info");
76
- }
77
- },
78
- });
79
- registerCursorProvider(pi, models);
80
- // Register last so session_shutdown cleanup remains protected until other Cursor handlers finish.
81
- registerCursorSdkSessionProcessErrorGuard(pi);
82
137
  }
@@ -183,7 +183,7 @@ npm run smoke:visual -- "${VISUAL_ARGS[@]}" \
183
183
  --prompt 'Stay in Cursor plan mode. If Cursor exposes plan, todo, task, or mode activity for this request, use that capability to outline a tiny unit test without editing files. Otherwise answer with a concise numbered plan. Do not use shell or file mutation tools.'
184
184
  ```
185
185
 
186
- By default, `npm run smoke:visual` writes `.ansi`, `.txt`, `.html`, `.png`, and `.jsonl.path` artifacts. If Playwright Chromium is unavailable in an agent-harness run, rerun with `--no-screenshot`, open the generated `.html` with `agent_browser`, save a PNG screenshot, and record that PNG path beside the runner artifacts. To visually audit bridge behavior or ambient Cursor settings, opt in with `--bridge`, `--bridge --expose-builtin-tools`, or `--setting-sources <value>` and label that evidence separately; do not count those opt-in runs as default native replay matrix proof.
186
+ By default, `npm run smoke:visual` writes `.ansi`, `.txt`, `.html`, `.png`, and `.jsonl.path` artifacts. The runner uses Playwright's Chromium or a system Chrome installation. If neither is available in an agent-harness run, rerun with `--no-screenshot`, open the generated `.html` with `agent_browser`, save a PNG screenshot, and record that PNG path beside the runner artifacts. To visually audit bridge behavior or ambient Cursor settings, opt in with `--bridge`, `--bridge --expose-builtin-tools`, or `--setting-sources <value>` and label that evidence separately; do not count those opt-in runs as default native replay matrix proof.
187
187
 
188
188
  Expected proof for each category is defined in [Cursor Native Tool Visual Audit Workflow](./cursor-native-tool-visual-audit.md). Do not mark a category passed because the prompt was sent. A category passes only when the PNG shows the expected card and the JSONL shows the expected completed `toolCall` / `toolResult` pair with the expected `isError` state.
189
189
 
@@ -29,7 +29,7 @@ Current implementation notes:
29
29
  - The bridge queues MCP calls, emits provider `toolcall_*` events, waits for matching pi `toolResult` messages by `toolCallId`, resolves the result back into the same live Cursor SDK run without creating a new `Agent`, and never calls tool `execute()` handlers directly. The same-run resume invariant holds unless the run was disposed, aborted, or cancelled.
30
30
  - Cursor SDK MCP tool calls use a guarded timeout override because installed `@cursor/sdk` 1.0.30 still has a 60-second MCP request default with no public per-server timeout option. The extension extends the verified Cursor SDK MCP `callTool` timeout path to 3600 seconds by default and shortens the verified first-send MCP initialize/listTools timeout paths to 10 seconds by default so unavailable configured MCP servers do not block the first reply for a full minute; unknown MCP protocol timeout stacks keep the SDK default. Users can override tool-call timeouts with `PI_CURSOR_MCP_TOOL_TIMEOUT_MS` or `PI_CURSOR_MCP_TOOL_TIMEOUT_SECONDS`, and initialize/listTools timeouts with `PI_CURSOR_MCP_CONNECT_TIMEOUT_MS` or `PI_CURSOR_MCP_CONNECT_TIMEOUT_SECONDS`. Bridged `CallTool` waits also have a local fail-closed deadline that defaults to and cannot exceed the effective MCP tool timeout; `PI_CURSOR_PI_BRIDGE_CALL_TIMEOUT_MS` can lower it, expiry or MCP cancellation aborts active pi execution when available, and expired bridge events are dropped before pi tool emission.
31
31
  - Cursor SDK local safety controls are off by default. `--cursor-auto-review` / `PI_CURSOR_AUTO_REVIEW` and `--cursor-sandbox` / `PI_CURSOR_SANDBOX` pass only explicit enabled values into `Agent.create({ local })`; user or trusted project config can set `local.autoReview` and `local.sandboxOptions.enabled`; project config is active only when Pi's project-trust flow reached the extension and approved the project or the run used explicit `--approve`, and project saves require the same immutable trust provenance rather than creating Pi trust resources automatically. Pi 0.84.0 loads `pi install -l` project-local extensions after the trust event, so those installs require `--approve` on every run that reads or writes `.pi/cursor-sdk.json`. Fast-default and HTTP transport saves preserve unrecognized config fields, reject malformed or non-object JSON without rewriting it, and use one lock-protected read-modify-write path; fast saves mutate only the selected model key. Because Pi can mutate its in-memory session branch before a journal append throws, a completed global save is authoritative and the command reports the partial journal failure instead of attempting an ambiguous rollback; the new global value stays authoritative over stale branch entries until a later successful save or session restart.
32
- - Local HTTP/1.1/SSE compatibility is strictly opt-in through `PI_CURSOR_HTTP_1_1`, `/cursor-http on|off|toggle`, or user `cursor-sdk.json` `local.useHttp1ForAgent`. Precedence is session, environment, user, then the built-in unset default; project config is excluded. Unset makes no `Cursor.configure()` call. Explicit values configure the installed SDK before local `Agent.create()`, extension-owned explicit state is cleared with the SDK's documented `null` reset when returning to unset and during session shutdown before module reload, and default/HTTP2/HTTP1 choices split pooled local agents. Pi's supported CLI/TUI/print/RPC lifecycle has one active session runtime per process; concurrent independent `AgentSession` embedding in one process is outside this transport toggle's contract because the installed SDK setting and executor cache are module-global. The footer adds `http1` only when HTTP/1.1 transport is enabled.
32
+ - Local HTTP/1.1/SSE compatibility is strictly opt-in through `PI_CURSOR_HTTP_1_1`, `/cursor-http on|off|toggle`, or user `cursor-sdk.json` `local.useHttp1ForAgent`. Precedence is session, environment, user, then the built-in unset default; project config is excluded. Unset makes no `Cursor.configure()` call. Explicit values configure the installed SDK before local `Agent.create()`, extension-owned explicit state is cleared with the SDK's documented `null` reset when returning to unset and during session shutdown before module reload, and default/HTTP2/HTTP1 choices split pooled local agents. Pi's supported CLI/TUI/print/RPC lifecycle has one active session runtime per process; concurrent independent `AgentSession` embedding in one process is outside this transport toggle's contract because the installed SDK setting and executor cache are module-global. The extension factory has process-owner and nested-child paths. The first load owns process-global controls, session scope, native replay state, and the owner SDK agent pool. A nested child `createAgentSession` load registers only a child-local Cursor provider, bridge, and SDK agent scope. This split keeps the parent bridge live and lets a Cursor child run without waiting on the busy parent SDK agent. The footer adds `http1` only when HTTP/1.1 transport is enabled.
33
33
  - 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.
34
34
  - 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.
35
35
  - Cursor internal tool activity is recorded from SDK events and scrubbed. Maintainer reference for `@cursor/sdk@1.0.30` `ToolType` values, runtime alias normalization, and intentional mapping/fallback rules: [Cursor native tool replay — SDK ToolType replay matrix](./cursor-native-tool-replay.md#sdk-tooltype-replay-matrix) (official SDK docs: https://cursor.com/docs/sdk/typescript). In TUI sessions and structured JSON/RPC modes, supported completed `read`, `bash`, `grep`, `find`, `ls`, `edit`, `write`, diagnostics, delete, todo/plan, task, image generation, MCP, semantic search, and screen recording activity is replayed through pi's native tool-call rendering path with recorded Cursor results, so users and JSON/RPC consumers can see native-looking cards/events 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/subagent, image, and MCP activity use neutral Cursor activity cards with pi's default success/error shell. Cursor SDK `task` activity is labeled **Cursor subagent** by default because it represents Cursor-spawned child-agent work; the card summary includes description plus subagent kind/model/short ID when Cursor reports them, and `PI_CURSOR_TASK_PRESENTATION=task` restores the older **Cursor task** wording for comparison. This is visibility over Cursor SDK task events, not a native pi subagent session: pi shows start/final output plus any `conversationSteps` tool-call summaries Cursor returns, but cannot show a live nested read/shell/MCP trail when the SDK only returns final subagent text. Neutral Cursor activity calls include `activityTitle` and, when available, `activitySummary` so partial/collapsed cards preserve identity such as `Cursor plan`, `Cursor todos`, `Cursor subagent`, `Cursor MCP`, or `Cursor edit`. For long-running or externally meaningful Cursor tools (`task`, `shell`, `mcp`, `generateImage`, `recordScreen`, `semSearch`, web search/fetch, plan/todo), the provider may surface one low-noise deferred in-progress thinking line such as `Cursor MCP: external_search` from bounded, scrubbed SDK args; fast local tools (`read`, `grep`, `glob`, and similar) skip lifecycle lines when completion follows immediately, and pi bridge MCP calls are excluded because pi already shows real pi tool execution ([lifecycle visibility](./cursor-native-tool-replay.md#low-noise-tool-lifecycle-visibility)). 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 mode/task/todo/plan activity 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 surfaced with bounded user-visible labels/traces (neutral activity cards when native replay routing allows, otherwise the same inactive or transcript trace fallbacks used for completed replay) instead of being silently discarded when the run failed, was aborted, or produced no assistant text; after a successful text-producing run, missing-completion starts remain maintainer-debug-only for all tools: installed `@cursor/sdk` 1.0.30 emits `tool-call-started` with no completion delta, step, or conversation entry when a permission policy or hook denies a call, and offers no way to distinguish such denials from lost completions, so suppression is the deliberate choice over false error cards. Explicit failures remain visible when Cursor reports them through completed tool calls or step results. Pi bridge MCP starts remain excluded from duplicate incomplete Cursor cards because pi already shows real pi tool execution. `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 also shown as bounded live progress while one shell call is active and used as display-only fallback for empty successful shell completions, while overlapping shell calls drop ambiguous deltas instead of guessing. Print mode keeps bounded scrubbed transcript output instead, preserving `pi -p` assistant text output. Cursor text deltas stream live when no live-run turn split is active.
@@ -76,7 +76,7 @@ npm install
76
76
  npx playwright install chromium
77
77
  ```
78
78
 
79
- `npx playwright install chromium` is only needed for automatic PNG capture. When running inside the pi agent harness, `agent_browser` is the preferred screenshot tool for generated HTML/ANSI output because it can open local files, verify saved artifacts, and capture exact evidence paths; in that case, run `npm run smoke:visual -- --no-screenshot ...` and screenshot the generated `.html` with `agent_browser`. Outside the harness, use Playwright through the checked-in runner.
79
+ Automatic PNG capture uses Playwright's Chromium or a system Chrome installation. If neither is available, run `npx playwright install chromium`. When running inside the pi agent harness, `agent_browser` is the preferred screenshot tool for generated HTML/ANSI output because it can open local files, verify saved artifacts, and capture exact evidence paths. In that case, run `npm run smoke:visual -- --no-screenshot ...` and screenshot the generated `.html` with `agent_browser`. Outside the harness, use Playwright through the checked-in runner.
80
80
 
81
81
  ## Runner contract
82
82
 
@@ -95,8 +95,8 @@ npx playwright install chromium
95
95
  - `TERM=xterm-256color`
96
96
  - cwd set to the target audit repo; the tmux session starts in `--cwd` with a non-login shell so a stale tmux-server cwd cannot print `getcwd` errors
97
97
  - `--session-id` forwarded to pi only when explicitly provided, so fresh captures avoid the new-session warning line
98
- - prompt paste plus carriage return into the interactive TUI
99
- - bounded post-prompt wait via `--wait-ms`
98
+ - prompt submitted after the Cursor TUI footer appears, using bracketed tmux paste and a literal carriage return
99
+ - bounded TUI readiness wait via `--startup-ms` and bounded post-submit wait via `--wait-ms`
100
100
  - artifacts outside the repo by default
101
101
  - `<label>.ansi`, `<label>.txt`, `<label>.html`, `<label>.png`, `<label>.jsonl.path`, and `<label>.manifest.json`
102
102
  - `--label`, `--ext`, `--cwd`, `--prompt`, `--prompt-file`, `--wait-ms`, and `--out-dir`
@@ -28,6 +28,30 @@ Passing hundreds of unit tests did not prove that chain was safe. Regression cov
28
28
 
29
29
  When changing provider/runtime behavior, ask whether the bug spans **pi extension lifecycle**, **active tool state**, **provider streaming**, and **persisted JSONL**. If yes, add an integration-style unit test or live smoke coverage for that chain.
30
30
 
31
+ ## In-process child sessions re-run the extension factory
32
+
33
+ Pi subagents build a child `AgentSession` in the same process (`createAgentSession` + `bindExtensions`). That re-invokes the `pi-cursor-sdk` factory against a new ExtensionAPI while the parent Cursor run still owns the process-global bridge, session scope, and pooled SDK agent.
34
+
35
+ The first observed failure: the child died at `0 tool uses` with no transcript file. The parent turn aborted with `This operation was aborted`. Bridge diagnostics showed `request_rejected` / `cancelled` with `Cursor pi tool bridge extension reloaded`.
36
+
37
+ The process-owner guard fixed that abort, but an unconditional nested-factory return introduced a second failure. A child that selected `cursor/grok-4.6` had model metadata from the parent but no `cursor` provider in its own model runtime. Pi reported `unrecognized provider error` before the first child turn.
38
+
39
+ Nested factories must split registration by ownership:
40
+
41
+ - The owner registers process-global controls, session state, native replay, and the owner bridge.
42
+ - Each nested child registers the Cursor provider on its own ExtensionAPI.
43
+ - Each nested child uses its own scope key and SDK agent pool entry. A Cursor child must not wait for the busy parent agent that is waiting for the subagent result.
44
+ - Each nested child uses its own bridge registry over the child's active pi tools. Child shutdown must not call the process-wide bridge abort path.
45
+ - Nested children disable local resume and native replay wrappers. They dispose their isolated SDK agent after the provider run completes.
46
+
47
+ Regression coverage:
48
+
49
+ - `test/cursor-extension-factory-guard.test.ts` — owner tokens reject stale release and release for every Pi shutdown reason
50
+ - `test/index-factory-guard.test.ts` — nested factories register only the child-local provider and bridge hooks without stealing owner scope
51
+ - `test/cursor-session-agent.test.ts` — a nested scope acquires its own SDK agent while the parent scope is busy
52
+ - `test/cursor-pi-tool-bridge.test.ts` — nested bridge shutdown does not reject a pending owner bridge call
53
+ - `test/cursor-provider-run-finalizer.test.ts` — live provider completion runs the nested lifecycle disposal path
54
+
31
55
  ## Dual-check invariant: `context.tools` vs pi active tools
32
56
 
33
57
  Native replay routing intentionally uses two layers:
@@ -434,7 +434,7 @@ Doctor checks:
434
434
  17. `tar` is available on macOS and native Windows.
435
435
  18. `node-pty` self-test passes on every target.
436
436
  19. Target pi tool probe proves the shell tool accepts platform-rendered commands on every target.
437
- 20. Host-side xterm/Playwright render self-test passes by rendering a minimal ANSI fixture through the repo xterm helper and launching Playwright Chromium to write a tiny PNG. If this fails, run `npm install` and `npx playwright install chromium` before live suites.
437
+ 20. Host-side xterm/Playwright render self-test passes by rendering a minimal ANSI fixture through the repo xterm helper and launching Playwright Chromium or system Chrome to write a tiny PNG. If neither browser is available, run `npm install` and `npx playwright install chromium` before live suites.
438
438
  21. `CURSOR_API_KEY` is present.
439
439
  22. Artifact root is writable.
440
440
  23. `git status --short` is recorded.