@cursor-harness-provider/native 0.0.0-stage → 0.4.6

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 (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/THIRD_PARTY_NOTICES.md +16 -0
  4. package/dist/cursor-protocol/auth/oauth.d.ts +65 -0
  5. package/dist/cursor-protocol/client/bridge.d.ts +86 -0
  6. package/dist/cursor-protocol/client/cursor-wire.d.ts +27 -0
  7. package/dist/cursor-protocol/client/h1-bridge.d.ts +23 -0
  8. package/dist/cursor-protocol/client/h2-proxy.d.ts +7 -0
  9. package/dist/cursor-protocol/client/h2-session.d.ts +54 -0
  10. package/dist/cursor-protocol/client/h2-unary.d.ts +23 -0
  11. package/dist/cursor-protocol/config/index.d.ts +24 -0
  12. package/dist/cursor-protocol/models/limits.d.ts +33 -0
  13. package/dist/cursor-protocol/models/parameterized.d.ts +98 -0
  14. package/dist/cursor-protocol/models/processing.d.ts +39 -0
  15. package/dist/cursor-protocol/proto/agent_pb.d.ts +13052 -0
  16. package/dist/cursor-protocol/stream/bridge-session.d.ts +30 -0
  17. package/dist/cursor-protocol/stream/client-transcript.d.ts +30 -0
  18. package/dist/cursor-protocol/stream/clipboard-images.d.ts +23 -0
  19. package/dist/cursor-protocol/stream/config.d.ts +5 -0
  20. package/dist/cursor-protocol/stream/context-normalize.d.ts +66 -0
  21. package/dist/cursor-protocol/stream/debug-log.d.ts +26 -0
  22. package/dist/cursor-protocol/stream/drift.d.ts +26 -0
  23. package/dist/cursor-protocol/stream/exec-native.d.ts +13 -0
  24. package/dist/cursor-protocol/stream/images.d.ts +24 -0
  25. package/dist/cursor-protocol/stream/interaction-query.d.ts +15 -0
  26. package/dist/cursor-protocol/stream/local-tool-policy.d.ts +73 -0
  27. package/dist/cursor-protocol/stream/message-parsing.d.ts +38 -0
  28. package/dist/cursor-protocol/stream/model-discovery.d.ts +50 -0
  29. package/dist/cursor-protocol/stream/model-routing.d.ts +30 -0
  30. package/dist/cursor-protocol/stream/native-core.d.ts +63 -0
  31. package/dist/cursor-protocol/stream/pi-adapter.d.ts +74 -0
  32. package/dist/cursor-protocol/stream/protocol.d.ts +23 -0
  33. package/dist/cursor-protocol/stream/recovery.d.ts +96 -0
  34. package/dist/cursor-protocol/stream/request-build.d.ts +134 -0
  35. package/dist/cursor-protocol/stream/root-prompt.d.ts +74 -0
  36. package/dist/cursor-protocol/stream/run-journal.d.ts +77 -0
  37. package/dist/cursor-protocol/stream/scope-journal.d.ts +43 -0
  38. package/dist/cursor-protocol/stream/server-messages.d.ts +49 -0
  39. package/dist/cursor-protocol/stream/session-state.d.ts +73 -0
  40. package/dist/cursor-protocol/stream/stream-writer.d.ts +6 -0
  41. package/dist/cursor-protocol/stream/thinking-filter.d.ts +19 -0
  42. package/dist/cursor-protocol/stream/tool-schema.d.ts +10 -0
  43. package/dist/cursor-protocol/stream/transport-errors.d.ts +29 -0
  44. package/dist/cursor-protocol/stream/tuning.d.ts +104 -0
  45. package/dist/cursor-protocol/stream/types.d.ts +339 -0
  46. package/dist/cursor-protocol/types/enums.d.ts +40 -0
  47. package/dist/cursor-protocol/utils/cache-dir.d.ts +6 -0
  48. package/dist/cursor-protocol/utils/security.d.ts +4 -0
  49. package/dist/index.d.ts +32 -0
  50. package/dist/index.js +15195 -0
  51. package/dist/index.js.map +7 -0
  52. package/dist/js-engine/engine.d.ts +88 -0
  53. package/dist/lifecycle.d.ts +25 -0
  54. package/dist/lifecycle.js +112 -0
  55. package/dist/lifecycle.js.map +7 -0
  56. package/licenses/distribution.json +12 -0
  57. package/licenses/pi-cursor/LICENSE +21 -0
  58. package/package.json +42 -4
@@ -0,0 +1,30 @@
1
+ import { type BridgeFactory, type BridgeHandle } from "../client/bridge.js";
2
+ import type { ActiveBridge } from "./types.js";
3
+ /** Test seam: the bridge factory used for both streaming and unary RPCs. */
4
+ export declare function getBridgeFactory(): BridgeFactory;
5
+ export declare const activeBridges: Map<string, ActiveBridge>;
6
+ export declare function setBridgeFactoryForTests(factory?: BridgeFactory): void;
7
+ export declare function clearActiveBridgeToolTimeout(active: ActiveBridge | undefined): void;
8
+ export declare function removeActiveBridge(bridgeKey: string): void;
9
+ export declare const idleBridges: Map<string, {
10
+ bridge: BridgeHandle;
11
+ idleTimer: ReturnType<typeof setTimeout>;
12
+ agentUrl?: string;
13
+ }>;
14
+ export declare function destroyIdleBridge(bridgeKey: string): void;
15
+ export declare function destroyAllIdleBridges(): void;
16
+ /** Keep a live HTTP/2 child around so the next user turn can skip spawn + TLS. */
17
+ export declare function parkIdleBridge(bridgeKey: string, bridge: BridgeHandle): void;
18
+ export declare function setActiveBridge(bridgeKey: string, active: Omit<ActiveBridge, "toolTimeoutTimer">): void;
19
+ /** Slide the parked-bridge TTL forward while the bridge is still useful. */
20
+ export declare function touchActiveBridge(bridgeKey: string): void;
21
+ export declare function makeHeartbeatBytes(): Uint8Array;
22
+ export declare function startBridge(accessToken: string, requestBytes: Uint8Array, options?: {
23
+ bridgeKey?: string;
24
+ agentUrl?: string;
25
+ }): {
26
+ bridge: BridgeHandle;
27
+ heartbeatTimer: NodeJS.Timeout;
28
+ };
29
+ export declare function sendCancelAction(bridge: BridgeHandle): void;
30
+ export declare function cleanupBridge(bridge: BridgeHandle, heartbeatTimer: ReturnType<typeof setInterval>, bridgeKey: string): void;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Pi's view of the turn in flight, as opposed to the wire history sent upstream.
3
+ *
4
+ * `live` means the wire current turn is Pi's own turn. `recovered` means recovery
5
+ * replaced the wire turn with a synthetic one, so Pi's turn is `inFlightTurn`
6
+ * extended by whatever the synthetic turn produces. Matching recovery against the
7
+ * bridge suffix after any earlier recovery is unrecoverable — the wire turn is
8
+ * only a suffix of Pi's turn, so exact tool-id matching could never succeed again.
9
+ */
10
+ import type { ClientTranscript, ParsedTurn, ToolResultInfo } from "./types.js";
11
+ export type { ClientTranscript } from "./types.js";
12
+ export declare function liveTranscript(completedTurns: ParsedTurn[]): ClientTranscript;
13
+ export declare function recoveredTranscript(completedTurns: ParsedTurn[], inFlightTurn: ParsedTurn): ClientTranscript;
14
+ /**
15
+ * Pi's in-flight turn as its next request will replay it: the tool calls it made, each with the
16
+ * result Pi sent back. Pi's parsed in-flight turn has the results stripped and listed beside it.
17
+ */
18
+ export declare function withToolResults(turn: ParsedTurn, toolResults: ToolResultInfo[]): ParsedTurn;
19
+ /**
20
+ * The turn Pi will report as completed once this stream finishes.
21
+ * After recovery the wire current turn is synthetic; Pi's in-flight turn is the
22
+ * recorded one extended by whatever steps the synthetic turn produced.
23
+ *
24
+ * A checkpoint is committed against this turn, not the wire one. Pi's next request is compared
25
+ * with what the checkpoint was recorded for, and Pi never saw the synthetic turn: its user text
26
+ * is recovered tool output, and its images are the tool results' images, not the question's.
27
+ */
28
+ export declare function clientInFlightTurn(transcript: ClientTranscript, wireCurrentTurn: ParsedTurn): ParsedTurn;
29
+ /** Mark that recovery replaced the wire current turn with a synthetic one. */
30
+ export declare function withSyntheticCurrentTurn(transcript: ClientTranscript, preRecoveryCurrentTurn: ParsedTurn): ClientTranscript;
@@ -0,0 +1,23 @@
1
+ import { type ImageDecodeOptions } from "./images.js";
2
+ import type { ParsedImageContent } from "./types.js";
3
+ export declare const PI_CLIPBOARD_IMAGE_NAME: RegExp;
4
+ /**
5
+ * `$TMPDIR/<clipboard-basename>` without following the file itself as a symlink.
6
+ * The parent directory may be realpath'd; a symlink at the leaf is rejected at open.
7
+ */
8
+ export declare function resolvedPiClipboardImagePath(absPath: string): string | undefined;
9
+ /** True when `absPath` is a Pi clipboard image sitting under the process temp dir. */
10
+ export declare function isPiClipboardImagePath(absPath: string): boolean;
11
+ /** Paths mentioned in user text whose basename is a Pi clipboard image. */
12
+ export declare function clipboardImagePathsInText(text: string): string[];
13
+ export type ClipboardImageRead = Uint8Array | "oversized" | undefined;
14
+ /**
15
+ * Open a Pi clipboard image without following a leaf symlink. Size is taken from
16
+ * the opened descriptor before any payload is allocated.
17
+ */
18
+ export declare function readPiClipboardImageBytes(absPath: string): ClipboardImageRead;
19
+ /**
20
+ * Load Pi clipboard images referenced in user text. Missing files are skipped.
21
+ * Oversized / unsupported images follow `ImageDecodeOptions` (throw vs drop).
22
+ */
23
+ export declare function loadClipboardImagesFromText(text: string, options?: ImageDecodeOptions): ParsedImageContent[];
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Cursor agent URL and version configuration.
3
+ * Re-exports from src/config/index.js for stream-layer backward compatibility.
4
+ */
5
+ export * from "../config/index.js";
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Normalize context-mode / session side-channel user messages into the system
3
+ * prompt so Cursor treats the real user turn as the task.
4
+ *
5
+ * Important: context-mode often appends injection text to the *same* user
6
+ * message as the real prompt ("hi\n\ncontext-mode active..."). Treating the
7
+ * whole message as side-channel swallows the real request. Mixed messages are
8
+ * split so only the infrastructure blocks move to the system prompt.
9
+ */
10
+ export type OpenAIRole = "system" | "user" | "assistant" | "tool";
11
+ export interface OpenAIContentPart {
12
+ type: string;
13
+ text?: string;
14
+ data?: string;
15
+ mimeType?: string;
16
+ image_url?: {
17
+ url?: string;
18
+ };
19
+ }
20
+ export interface OpenAIMessage {
21
+ role: OpenAIRole;
22
+ content?: string | OpenAIContentPart[] | null;
23
+ tool_call_id?: string;
24
+ name?: string;
25
+ tool_calls?: unknown[];
26
+ /** Carried through untouched; see OpenAIMessage in ./types.ts. */
27
+ interrupted_notice?: string;
28
+ /** Replayed thinking from a prior assistant turn. */
29
+ thinking?: string;
30
+ }
31
+ export declare function textContent(content: OpenAIMessage["content"]): string;
32
+ export declare function contentHasImageParts(content: OpenAIMessage["content"]): boolean;
33
+ export declare function isContextModeSideChannelText(text: string): boolean;
34
+ /**
35
+ * True when the entire message is infrastructure-only (no residual user task).
36
+ * Mixed messages that *contain* side-channel markers still return false here if
37
+ * there is leading/trailing user text after splitting.
38
+ */
39
+ export declare function isPureContextModeSideChannelText(text: string): boolean;
40
+ /**
41
+ * True when a side-channel carries no useful session memory — only the standard
42
+ * context-mode hierarchy blurb and/or an empty/mode-only session_state.
43
+ * These add tokens without helping the model and should be dropped.
44
+ */
45
+ export declare function isNoOpSideChannelText(text: string): boolean;
46
+ /**
47
+ * Split a user message that may concatenate real task text with context-mode /
48
+ * session_state injections.
49
+ */
50
+ export declare function splitUserTextAndSideChannel(text: string): {
51
+ userText: string;
52
+ sideText: string;
53
+ };
54
+ /**
55
+ * True when a side-channel carries a compaction summary or session-resume memory
56
+ * that the model must treat as prior work, not as disposable infrastructure.
57
+ */
58
+ export declare function isResumeOrCompactionSideChannel(text: string): boolean;
59
+ /** True when the system prompt holds folded session/compaction memory that a greeting must not drop. */
60
+ export declare function systemPromptHasSessionMemory(systemPrompt: string): boolean;
61
+ export declare function frameContextModeSideChannel(text: string): string;
62
+ /**
63
+ * Fold pure side-channel user messages into the system prompt and keep the
64
+ * real user turns as the task. Mixed user messages are split in place.
65
+ */
66
+ export declare function normalizeMessagesForCursor(messages: OpenAIMessage[]): OpenAIMessage[];
@@ -0,0 +1,26 @@
1
+ import type { CursorRequestDebugSummary } from "./types.js";
2
+ export declare const requestDebugByBody: WeakMap<Uint8Array<ArrayBufferLike>, CursorRequestDebugSummary>;
3
+ export declare function isStreamDebugEnabled(): boolean;
4
+ export declare function truncateDebugString(value: string, max?: number): string;
5
+ export declare function debugByteSummary(bytes: Uint8Array): {
6
+ byteLength: number;
7
+ sha256: string;
8
+ };
9
+ export declare function debugBase64ImageSummary(data: string): {
10
+ base64Length: number;
11
+ byteLength?: number;
12
+ sha256?: string;
13
+ decodeError?: boolean;
14
+ };
15
+ export declare function sanitizeForDebug(value: unknown): unknown;
16
+ export declare function getDebugLogFilePath(): string;
17
+ export declare function debugLog(event: string, data?: Record<string, unknown>): void;
18
+ export declare function getLifecycleLogPath(): string;
19
+ export declare function lifecycleLog(event: string, data?: Record<string, unknown>): void;
20
+ export type MetricEmitter = (event: string, data: Record<string, unknown>) => void;
21
+ export declare function emitMetric(event: string, data: Record<string, unknown>): void;
22
+ export declare function nextDebugRequestId(): string;
23
+ export declare function decodeRequestForTests(requestBody: Uint8Array): CursorRequestDebugSummary;
24
+ export declare function redactForDebug(value: string): string;
25
+ /** Test seam: replace the metric sink (used by __testInternals). */
26
+ export declare function setMetricEmitter(factory?: MetricEmitter): void;
@@ -0,0 +1,26 @@
1
+ import { DriftKind, type DriftKindType } from "../types/enums.js";
2
+ export { DriftKind, type DriftKindType } from "../types/enums.js";
3
+ export interface DriftSignal {
4
+ kind: DriftKind;
5
+ detail: string;
6
+ count: number;
7
+ firstSeenIso: string;
8
+ lastSeenIso: string;
9
+ }
10
+ /**
11
+ * Records one drift observation. Safe to call on a hot path: repeat observations
12
+ * only bump a counter, and only the first of each kind+detail is logged.
13
+ */
14
+ export declare function recordDriftSignal(kind: DriftKind | DriftKindType, detail: string | undefined): void;
15
+ /**
16
+ * Records unknown protobuf fields on a decoded message. `$unknown` is populated
17
+ * by @bufbuild/protobuf whenever the wire carries fields our schema lacks, which
18
+ * is the earliest signal that `proto/agent.proto` is behind Cursor.
19
+ */
20
+ export declare function recordUnknownFields(context: string, message: unknown): void;
21
+ export declare function getDriftSignals(): DriftSignal[];
22
+ /** True when something was seen that can actually strand a turn. */
23
+ export declare function hasStrandingDrift(): boolean;
24
+ /** One-line summary for `/cursor.doctor` and error messages; empty when clean. */
25
+ export declare function formatDriftSummary(limit?: number): string;
26
+ export declare function resetDriftSignalsForTests(): void;
@@ -0,0 +1,13 @@
1
+ export type NativeExecFrame = {
2
+ resultCase: string;
3
+ value: unknown;
4
+ };
5
+ export type NativeExecDispatch = {
6
+ kind: "sync";
7
+ frame: NativeExecFrame;
8
+ } | {
9
+ kind: "async";
10
+ run: () => Promise<NativeExecFrame>;
11
+ };
12
+ /** Dispatches retained native handlers; local file and shell operations have no executor here. */
13
+ export declare function dispatchNativeExec(execCase: string, args: Record<string, unknown>): NativeExecDispatch | undefined;
@@ -0,0 +1,24 @@
1
+ import type { ParsedImageContent } from "./types.js";
2
+ export declare const CURSOR_CLI_MAX_IMAGE_BYTES = 5242880;
3
+ export declare const CURSOR_SUPPORTED_IMAGE_MIME_TYPES: Set<string>;
4
+ export interface ImageDecodeOptions {
5
+ enforceCursorCliLimits?: boolean;
6
+ /**
7
+ * Return `undefined` instead of throwing when an image fails Cursor's limits.
8
+ *
9
+ * Rejecting loudly is right for the image a caller is attaching right now — they can resize it.
10
+ * It is wrong for images already sitting in the transcript: those are unfixable, and since the
11
+ * whole history is re-parsed on every request, one bad image would otherwise fail not just its
12
+ * own turn but every turn after it, permanently.
13
+ */
14
+ dropInvalid?: boolean;
15
+ }
16
+ export declare function normalizeImageMimeType(mimeType: string): string;
17
+ export declare function sniffCursorImageMimeType(bytes: Uint8Array): string | undefined;
18
+ export declare function validateCursorCliImageLimits(bytes: Uint8Array): string;
19
+ export declare function decodeImageBytes(bytes: Uint8Array, options?: ImageDecodeOptions): ParsedImageContent | undefined;
20
+ export declare function decodeBase64Image(data: string, mimeType: string, options?: ImageDecodeOptions): ParsedImageContent | undefined;
21
+ export declare function parseImageDataUrl(url: string, options?: ImageDecodeOptions): ParsedImageContent | undefined;
22
+ export declare function imageKey(image: ParsedImageContent): string;
23
+ export declare function mergeImages(...groups: Array<ParsedImageContent[] | undefined>): ParsedImageContent[] | undefined;
24
+ export declare function cloneParsedImage(image: ParsedImageContent): ParsedImageContent;
@@ -0,0 +1,15 @@
1
+ import { type InteractionQuery } from "../proto/agent_pb.js";
2
+ export type InteractionQueryHandleResult = {
3
+ handled: boolean;
4
+ action: string;
5
+ queryCase: string | undefined;
6
+ };
7
+ /**
8
+ * Always attempt to answer InteractionQuery so the upstream run does not park.
9
+ * Web/search is approved so Cursor-hosted fetch/search can complete the turn
10
+ * instead of forcing the model to re-plan through Pi tools. Pass
11
+ * `{ approveWeb: false }` to reject those prompts.
12
+ */
13
+ export declare function handleInteractionQuery(query: InteractionQuery, sendFrame: (data: Uint8Array) => void, options?: {
14
+ approveWeb?: boolean;
15
+ }): InteractionQueryHandleResult;
@@ -0,0 +1,73 @@
1
+ import { type McpToolDefinition } from "../proto/agent_pb.js";
2
+ /**
3
+ * How often the model may come back to a disabled native tool before the run is stopped.
4
+ *
5
+ * The unit is a model step, not a call. A model that issues twelve native calls in parallel has
6
+ * not ignored twelve rejections: Cursor executes each call as it streams in, so all twelve are
7
+ * rejected before the model reads the first reply. Counting calls stopped such a turn with
8
+ * nothing executed. Cursor checkpoints the conversation once a step's tool results are in, and
9
+ * that checkpoint is what separates one step's rejections from the next (see
10
+ * `closeLocalToolRejectionStep`).
11
+ */
12
+ export declare const MAX_LOCAL_TOOL_REJECTION_STEPS = 8;
13
+ /**
14
+ * Hard ceiling on rejected calls, whatever the step count. It keeps the loop finite if Cursor
15
+ * ever stops sending the checkpoint the step count relies on.
16
+ */
17
+ export declare const MAX_LOCAL_TOOL_REJECTIONS = 64;
18
+ /** The rejection counters, as carried by a stream's state and across its transport retries. */
19
+ export interface LocalToolRejectionBudget {
20
+ /** Rejected native calls since the last Pi result. */
21
+ localToolRejections?: number;
22
+ /** Model steps with at least one rejected native call since the last Pi result. */
23
+ localToolRejectionSteps?: number;
24
+ /** True while further rejections belong to the step already counted. */
25
+ localToolRejectionStepOpen?: boolean;
26
+ }
27
+ /** Counts one rejected native call, and its model step if this is the step's first rejection. */
28
+ export declare function recordLocalToolRejection(budget: LocalToolRejectionBudget): void;
29
+ /** Call on a conversation checkpoint: the model has now been shown the step's rejections. */
30
+ export declare function closeLocalToolRejectionStep(budget: LocalToolRejectionBudget): void;
31
+ export declare function localToolLoopExhausted(budget: LocalToolRejectionBudget): boolean;
32
+ export declare function localToolLoopError(budget: LocalToolRejectionBudget): string;
33
+ /**
34
+ * Header Cursor's agent server reads to limit a run's built-in toolset, as the Cursor CLI sends
35
+ * it for `--allowed-tools`: `ToolCall` oneof field names, comma-joined. Its counterpart for
36
+ * `--exclude-tools` (`x-cursor-agent-exclude-tools`) is not honored on this client's runs: live,
37
+ * the model still listed Shell, Read, Grep and Glob with it set, and none with this one.
38
+ */
39
+ export declare const CURSOR_ALLOWED_TOOLS_HEADER = "x-cursor-agent-allowed-tools";
40
+ /**
41
+ * The built-in tools this provider can serve. Pi tools are MCP tools, reached through
42
+ * CallDynamicTool (`mcp_tool_call`) after GetDynamicTools (`get_mcp_tools_tool_call`); fetch is
43
+ * answered on the stream and web search is approved. Everything else, local file and shell
44
+ * operations above all, would only be rejected, so the model never sees it and cannot spend a
45
+ * step on a refused call.
46
+ */
47
+ export declare const ALLOWED_CURSOR_TOOLS: readonly ["mcp_tool_call", "get_mcp_tools_tool_call", "fetch_tool_call", "web_fetch_tool_call", "web_search_tool_call"];
48
+ /** `PI_CURSOR_NATIVE_TOOLS=1` keeps Cursor's full built-in toolset in the run (rejected on use). */
49
+ export declare function isNativeToolsetEnabled(envValue?: string | undefined): boolean;
50
+ /** Request headers for an `AgentService/Run` stream. */
51
+ export declare function cursorRunHeaders(): Record<string, string>;
52
+ /** Identifies native file and shell requests that must be rejected in favor of Pi tools. */
53
+ export declare function isLocalToolExec(execCase: string): boolean;
54
+ /** Caches nonempty tool names and aliases; the definitions array must remain immutable. */
55
+ export declare function availableToolNamesFor(tools: McpToolDefinition[]): string[];
56
+ /**
57
+ * The Pi catalog as sent in RunRequest and RequestContext, under the wire names of
58
+ * `cursorMcpToolNames`. The registry passed to dispatch keeps Pi's own names.
59
+ */
60
+ export declare function wireMcpToolDefinitions(tools: McpToolDefinition[]): McpToolDefinition[];
61
+ /** Lists registered tools with known matches first, custom tools visible, and bash last. */
62
+ export declare function localToolCandidates(execCase: string, tools: McpToolDefinition[]): string[];
63
+ /**
64
+ * Tells the model how Pi tools are invoked and publishes each tool's schema, so it can call
65
+ * `CallDynamicTool` directly instead of trying native tools or calling `GetDynamicTools` on
66
+ * every turn. Live probes on DeepSeek and Grok removed every lookup and native retry with
67
+ * this catalog; names alone still left one lookup per turn.
68
+ */
69
+ export declare function dynamicToolCatalogText(tools: McpToolDefinition[]): string;
70
+ /** Explains a native rejection using registered tools and their schemas, or the current lack of tools. */
71
+ export declare function nativeToolRejectReason(execCase: string, tools: McpToolDefinition[]): string;
72
+ /** Builds prompt guidance for Pi-owned local operations, including tool-free requests. */
73
+ export declare function localToolPolicyText(tools: McpToolDefinition[]): string;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Turns Pi's OpenAI-shaped message list into the turn structure Cursor expects.
3
+ *
4
+ * Cursor's agent protocol is turn-oriented (user text + assistant steps + tool
5
+ * results), not a flat message array, so this module regroups messages into
6
+ * `ParsedTurn`s, reattaches tool-result images to the call that produced them,
7
+ * and folds context-mode side-channel messages into the system prompt.
8
+ */
9
+ import type { JsonObject } from "@earendil-works/pi-ai";
10
+ import { type ImageDecodeOptions } from "./images.js";
11
+ import type { CursorToolResultImagePayload, OpenAIMessage, ParsedImageContent, ParsedMessages, ParsedToolCallStep, ParsedToolResult, ParsedTurn, ParsedTurnStep } from "./types.js";
12
+ export declare function textContent(content: OpenAIMessage["content"]): string;
13
+ export declare function contentHasImageParts(content: OpenAIMessage["content"]): boolean;
14
+ export declare function imageContent(content: OpenAIMessage["content"], options?: ImageDecodeOptions): ParsedImageContent[];
15
+ export declare function parseToolResultImagePayloads(payloads: CursorToolResultImagePayload[] | undefined): Map<string, ParsedImageContent[]>;
16
+ export declare function isSyntheticToolResultImageMessage(msg: OpenAIMessage): boolean;
17
+ export type ToolCallStepWithResult = ParsedToolCallStep & {
18
+ result: ParsedToolResult;
19
+ };
20
+ export declare function isToolCallStepWithResult(step: ParsedTurnStep): step is ToolCallStepWithResult;
21
+ export declare function attachSyntheticToolResultImages(turn: ParsedTurn, images: ParsedImageContent[]): void;
22
+ export declare function normalizeToolResultText(content: string, images: ParsedImageContent[] | undefined): string;
23
+ export declare function parseToolCallArguments(raw: string): JsonObject;
24
+ export declare function isToolCallStep(step: ParsedTurnStep): step is ParsedToolCallStep;
25
+ export declare function getTurnToolCallResults(turn: ParsedTurn): Map<string, ParsedToolResult>;
26
+ export declare function appendAssistantTextToTurn(turn: ParsedTurn, text: string): void;
27
+ export declare function stripTurnRuntimeState(turn: ParsedTurn & {
28
+ toolCallById?: Map<string, ParsedToolCallStep>;
29
+ sawToolResult?: boolean;
30
+ sawAssistantAfterToolResult?: boolean;
31
+ }): ParsedTurn;
32
+ export declare function clonePlainValue(value: unknown): unknown;
33
+ export declare function stripInFlightResults(turn: ParsedTurn): ParsedTurn;
34
+ export declare function isContextModeSideChannelText(text: string): boolean;
35
+ export declare function frameContextModeSideChannel(text: string): string;
36
+ export declare function systemPromptHasSessionMemory(systemPrompt: string): boolean;
37
+ export declare function normalizeMessagesForCursor(messages: OpenAIMessage[]): OpenAIMessage[];
38
+ export declare function parseMessages(messages: OpenAIMessage[], toolResultImagePayloads?: CursorToolResultImagePayload[]): ParsedMessages;
@@ -0,0 +1,50 @@
1
+ import { type CursorModelParameter, type CursorParameterizedModel } from "../client/cursor-wire.js";
2
+ export declare function callCursorUnaryRpc(options: {
3
+ accessToken: string;
4
+ rpcPath: string;
5
+ requestBody: Uint8Array;
6
+ url?: string;
7
+ timeoutMs?: number;
8
+ signal?: AbortSignal;
9
+ }): Promise<{
10
+ body: Uint8Array;
11
+ exitCode: number;
12
+ timedOut: boolean;
13
+ }>;
14
+ export interface CursorModel {
15
+ id: string;
16
+ name: string;
17
+ reasoning: boolean;
18
+ contextWindow: number;
19
+ maxTokens: number;
20
+ requestedModelId?: string;
21
+ parameters?: CursorModelParameter[];
22
+ requiresMaxMode?: boolean;
23
+ requestedMaxMode?: boolean;
24
+ supportsImages?: boolean;
25
+ /** Cursor API metadata-only rows are catalog bookkeeping, never user-selectable. */
26
+ metadataOnly?: boolean;
27
+ }
28
+ export declare function getCursorModels(apiKey: string, options?: {
29
+ signal?: AbortSignal;
30
+ url?: string;
31
+ }): Promise<CursorModel[]>;
32
+ export declare function getCursorParameterizedModels(apiKey: string, options?: {
33
+ signal?: AbortSignal;
34
+ }): Promise<CursorParameterizedModel[]>;
35
+ export interface CursorCatalog {
36
+ rawModels: CursorModel[];
37
+ parameterizedModels: CursorParameterizedModel[];
38
+ }
39
+ /**
40
+ * Run both discovery RPCs.
41
+ *
42
+ * The cross-process catalog cache was removed with the legacy extension that
43
+ * read it: Pi persists catalogs through its own models store and OpenCode
44
+ * refetches at startup, so nothing consumed `readCachedCatalog` and the write
45
+ * was dead weight.
46
+ */
47
+ export declare function discoverCursorCatalog(apiKey: string, options?: {
48
+ signal?: AbortSignal;
49
+ url?: string;
50
+ }): Promise<CursorCatalog>;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Model ID effort suffix routing for Cursor runtime variants.
3
+ */
4
+ export interface CursorNativeModelRouting {
5
+ modelId: string;
6
+ parameters?: Array<{
7
+ id: string;
8
+ value: string;
9
+ }>;
10
+ requiresMaxMode?: boolean;
11
+ requestedMaxMode?: boolean;
12
+ }
13
+ export interface ResolvedCursorModelRouting extends CursorNativeModelRouting {
14
+ maxMode: boolean;
15
+ }
16
+ type CursorModelRoutingByEffort = Record<string, CursorNativeModelRouting>;
17
+ export interface CursorResolvableModel {
18
+ id: string;
19
+ [key: string]: unknown;
20
+ }
21
+ /**
22
+ * Insert reasoning effort into model ID, before -fast/-thinking suffix.
23
+ * e.g. model="gpt-5.4" + effort="medium" → "gpt-5.4-medium"
24
+ * model="gpt-5.4-fast" + effort="high" → "gpt-5.4-high-fast"
25
+ * If no effort provided, returns model as-is.
26
+ */
27
+ export declare function resolveModelId(model: string, reasoningEffort?: string): string;
28
+ export declare function resolveRequestedModelId(model: string, reasoningEffort?: string, cursorModelId?: string): string;
29
+ export declare function resolveRequestedModelId(model: CursorResolvableModel, reasoningEffort?: string, routingByModelId?: Map<string, CursorModelRoutingByEffort | CursorNativeModelRouting>): ResolvedCursorModelRouting;
30
+ export {};
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Cursor native provider runtime: translates Pi streamSimple context to Cursor's
3
+ * protobuf/HTTP2 Connect protocol.
4
+ *
5
+ * Based on https://github.com/ephraimduncan/opencode-cursor by Ephraim Duncan.
6
+ * Uses an in-process node:http2 client (src/client/h2-session.ts) — no subprocess.
7
+ */
8
+ import { type Api, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions } from "@earendil-works/pi-ai";
9
+ import { type McpToolDefinition } from "../proto/agent_pb.js";
10
+ import { type BridgeHandle } from "../client/bridge.js";
11
+ import type { CursorModelParameter } from "../client/cursor-wire.js";
12
+ export type { CursorModelParameter, CursorParameterizedModel, CursorParameterizedVariant, } from "../client/cursor-wire.js";
13
+ import { discardStaleCheckpointIfNeeded, fingerprintCompletedTurns, persistAbortedConversationState, trimBlobStore } from "./session-state.js";
14
+ export { cleanupAllSessionState, commitStoredCheckpointMidPause, deriveBridgeKey, deriveConversationKey, derivePiSessionId, deterministicConversationId, evictStaleConversations, fingerprintCompletedTurns, handleBridgeCloseMidPause, type HandleBridgeCloseMidPauseInput, } from "./session-state.js";
15
+ export { buildCursorRequest, isIdentityConversationalTurn, isTrivialConversationalTurn, summarizeRequestSize, type BuildCursorRequestOptions, } from "./request-build.js";
16
+ export { hashSystemPrompt } from "./root-prompt.js";
17
+ export { isContextModeSideChannelText, normalizeMessagesForCursor, parseMessages, systemPromptHasSessionMemory, } from "./message-parsing.js";
18
+ export { discoverCursorCatalog, getCursorModels, getCursorParameterizedModels, type CursorCatalog, type CursorModel, } from "./model-discovery.js";
19
+ export { setBridgeFactoryForTests } from "./bridge-session.js";
20
+ import { createStreamIdleWatchdog } from "./tuning.js";
21
+ export { canBlindIdleRestart, canRecoverAfterTransportLoss, interactionUpdateProgress, resolveH2ConnectTimeoutMs, resolveH2IdleTimeoutMs, resolveResumeIdleTimeoutMs, resolveStreamIdleMaxRetries, resolveStreamIdleTimeoutMs, } from "./tuning.js";
22
+ export { CHECKPOINT_CONTINUATION_PROMPT, classifyBridgeExit, formatTransportFailure, type TransportFailure, } from "./transport-errors.js";
23
+ import { type RecoveryDecision, type PlanRecoveryInput } from "./recovery.js";
24
+ import type { ActiveBridge, CheckpointRef, ClientTranscript, CursorNativeStreamConfig, CursorNativeStreamOptions, CursorRunUsage, NativeStreamWriter, ParsedTurn, PendingExec, StreamIdleRetryController, ToolResultInfo } from "./types.js";
25
+ export type { CursorNativeStreamConfig, ParsedAssistantTextStep, ParsedImageContent, ParsedToolCallStep, ParsedToolResult, ParsedTurn, ParsedTurnStep, StoredConversation, } from "./types.js";
26
+ export declare const __testInternals: {
27
+ conversationStates: Map<string, import("./types.js").StoredConversation>;
28
+ createStreamIdleWatchdog: typeof createStreamIdleWatchdog;
29
+ discardStaleCheckpointIfNeeded: typeof discardStaleCheckpointIfNeeded;
30
+ fingerprintCompletedTurns: typeof fingerprintCompletedTurns;
31
+ persistAbortedConversationState: typeof persistAbortedConversationState;
32
+ trimBlobStore: typeof trimBlobStore;
33
+ writeNativeStream: typeof writeNativeStream;
34
+ handleNativeToolResultResume: typeof handleNativeToolResultResume;
35
+ };
36
+ export declare function planRecovery(input: PlanRecoveryInput): RecoveryDecision;
37
+ export declare function createCursorNativeStream(config: CursorNativeStreamConfig): (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;
38
+ /**
39
+ * Consumes one bridge stream, yielding Pi calls and enforcing the rejection budget across retries.
40
+ * The budget counts model steps that hit a disabled native tool, not calls: local-tool-policy.ts.
41
+ */
42
+ declare function writeNativeStream(bridge: BridgeHandle, heartbeatTimer: ReturnType<typeof setInterval>, blobStore: Map<string, Uint8Array>, mcpTools: McpToolDefinition[], _model: Model<Api>, modelId: string, bridgeKey: string, convKey: string, completedTurns: ParsedTurn[], currentTurn: ParsedTurn, writer: NativeStreamWriter, options?: CursorNativeStreamOptions, requestId?: string, idleRetry?: StreamIdleRetryController, streamIdleTimeoutMs?: number, checkpointRef?: CheckpointRef, preservedMidPauseExecs?: PendingExec[], clientTranscript?: ClientTranscript, runUsage?: CursorRunUsage): void;
43
+ interface ResumeContext {
44
+ accessToken: string;
45
+ systemPrompt: string;
46
+ model: Model<Api>;
47
+ modelId: string;
48
+ bridgeKey: string;
49
+ convKey: string;
50
+ sessionId: string | undefined;
51
+ completedTurns: ParsedTurn[];
52
+ /** Pi's in-flight turn from the resume request, not the bridge's currentTurn suffix. */
53
+ inFlightTurn?: ParsedTurn;
54
+ maxMode: boolean;
55
+ cursorModelParameters: CursorModelParameter[];
56
+ getAccessToken?: (options?: {
57
+ forceRefresh?: boolean;
58
+ }) => Promise<string>;
59
+ /** Endpoint the active bridge was opened against, for rebuilt transports. */
60
+ agentUrl?: string;
61
+ }
62
+ /** Collects pending Pi results and resumes Cursor with a fresh budget once all results are sent. */
63
+ declare function handleNativeToolResultResume(active: ActiveBridge, toolResults: ToolResultInfo[], ctx: ResumeContext, writer: NativeStreamWriter, options?: CursorNativeStreamOptions, requestId?: string): void;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Translation between Pi's context/model types and the OpenAI-shaped request
3
+ * this provider builds Cursor calls from.
4
+ *
5
+ * Everything Pi-facing lives here: content-block narrowing, tool definitions,
6
+ * usage/cost accounting on the assistant message, and reasoning-effort routing
7
+ * onto Cursor's model variants. Nothing in this module touches the wire.
8
+ */
9
+ import type { Api, AssistantMessage, Context, ImageContent as PiImageContent, Message as PiMessage, Model, TextContent as PiTextContent, Tool as PiTool, ToolCall as PiToolCall } from "@earendil-works/pi-ai";
10
+ import type { CursorNativeModelRouting } from "./model-routing.js";
11
+ import type { ChatCompletionRequest, CursorRunUsage, CursorNativeStreamConfig, CursorNativeStreamOptions, OpenAIMessage, OpenAIToolCall, OpenAIToolDef, StreamState } from "./types.js";
12
+ export declare function emptyCursorUsage(): AssistantMessage["usage"];
13
+ export declare function tokenCost(tokens: number, ratePerMillion?: number): number;
14
+ export declare function applyCursorUsage(output: AssistantMessage, model: Model<Api>, state?: StreamState): void;
15
+ export declare function emptyCursorRunUsage(): CursorRunUsage;
16
+ export declare function createCursorAssistantMessage(model: Model<Api>): AssistantMessage;
17
+ export declare function isPiTextContent(block: unknown): block is PiTextContent;
18
+ export declare function isPiImageContent(block: unknown): block is PiImageContent;
19
+ export declare function isPiToolCall(block: unknown): block is PiToolCall;
20
+ export declare function isPiThinkingContent(block: unknown): block is {
21
+ type: "thinking";
22
+ thinking: string;
23
+ };
24
+ export declare function piContentToOpenAIContent(content: string | PiMessage["content"]): OpenAIMessage["content"];
25
+ export declare function assistantTextFromPiContent(content: AssistantMessage["content"]): string;
26
+ export declare function assistantThinkingFromPiContent(content: AssistantMessage["content"]): string;
27
+ export declare function assistantToolCallsFromPiContent(content: AssistantMessage["content"]): OpenAIToolCall[];
28
+ /** Longest error detail carried into the replayed notice. */
29
+ export declare const MAX_INTERRUPTED_NOTICE_ERROR_CHARS = 200;
30
+ /**
31
+ * Describe a prior assistant turn that never ran to completion.
32
+ *
33
+ * Cursor's turn structure only carries the text a turn produced, so an aborted
34
+ * or failed turn replays as one that simply trails off — indistinguishable from
35
+ * a model that chose to stop. Observed effect on a resumed session: the model
36
+ * reads the gap as missing context and goes looking for it (re-listing the
37
+ * workspace, reading unrelated transcripts) instead of continuing the work.
38
+ *
39
+ * Returns "" for turns that completed normally, which is the common case.
40
+ */
41
+ export declare function interruptedAssistantNotice(message: {
42
+ stopReason?: AssistantMessage["stopReason"];
43
+ errorMessage?: string;
44
+ }): string;
45
+ export declare function piToolToOpenAI(tool: PiTool): OpenAIToolDef;
46
+ export declare function resolveNativeReasoningEffort(model: Model<Api>, options: CursorNativeStreamOptions | undefined, noReasoningEffortByModelId?: Map<string, string>): string | undefined;
47
+ export declare function applyNativeCursorRouting(body: ChatCompletionRequest, rawRoutingByModelId?: Map<string, Record<string, CursorNativeModelRouting>>): void;
48
+ export interface TranscriptInputs {
49
+ systemPrompt: string;
50
+ tools: PiTool[];
51
+ }
52
+ /**
53
+ * pi-ai 0.86 stopped handing providers `context.systemPrompt` / `context.tools`
54
+ * and now carries both as deltas on the transcript's system messages
55
+ * (`normalizeContext` builds a `{ messages }` object and drops the rest).
56
+ * The replay is reimplemented rather than imported from `getCurrentTools` /
57
+ * `getCurrentSystemPrompt`: pi-ai is an external peer dependency, so a named
58
+ * import missing on 0.85.x would be an ESM link error that kills the whole
59
+ * extension. Presence of a system message — not truthiness of `context.tools` —
60
+ * selects the shape, so a 0.86 turn that legitimately declares no tools is not
61
+ * mistaken for a legacy context.
62
+ */
63
+ export declare function resolveTranscriptInputs(context: Context): TranscriptInputs;
64
+ export declare function contextToCursorChatCompletionRequest(model: Model<Api>, context: Context, options: CursorNativeStreamOptions | undefined, config: CursorNativeStreamConfig): ChatCompletionRequest;
65
+ export declare function resolveToolsForToolChoice(tools: OpenAIToolDef[], toolChoice: unknown): {
66
+ tools: OpenAIToolDef[];
67
+ } | {
68
+ error: string;
69
+ };
70
+ export declare function computeUsage(state: StreamState): {
71
+ prompt_tokens: number;
72
+ completion_tokens: number;
73
+ total_tokens: number;
74
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Protocol-drift helpers: auth error detection, decode error framing, client version.
3
+ */
4
+ import type { CursorErrorDetail } from "../client/bridge.js";
5
+ export declare function isAuthErrorMessage(message: string): boolean;
6
+ export declare function isProtocolMismatchMessage(message: string): boolean;
7
+ export declare function formatProtocolMismatchHint(message: string): string;
8
+ /**
9
+ * Appends what actually drifted, when anything did.
10
+ *
11
+ * A turn that fails after we skipped an unrecognized server message would
12
+ * otherwise surface as a bare timeout. Naming the unhandled case turns "it hung"
13
+ * into a reproducible bug report.
14
+ */
15
+ export declare function appendDriftDiagnostic(message: string): string;
16
+ /** Cursor's own explanation of a failure as a bracketed note; empty when it sent none. */
17
+ export declare function formatCursorErrorDetail(detail: CursorErrorDetail | undefined): string;
18
+ /**
19
+ * Adds the hints a failed stream deserves. `message` alone decides which: Cursor's detail text is
20
+ * free-form (a provider status of 401 is not an expired Pi token), so it is appended, never
21
+ * matched.
22
+ */
23
+ export declare function enhanceCursorStreamError(message: string, detail?: CursorErrorDetail): string;