@playwo/opencode-cursor-oauth 0.0.0-dev.2c48be2f48c9 → 0.0.0-dev.4258a6733133

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.
@@ -79,6 +79,11 @@ export function parseMessages(messages) {
79
79
  completedTurnStates = parsedTurns.slice(0, -1);
80
80
  userText = lastTurn.userText;
81
81
  }
82
+ else if (lastTurn.userText && hasAssistantSummary) {
83
+ completedTurnStates = parsedTurns.slice(0, -1);
84
+ userText = lastTurn.userText;
85
+ pendingAssistantSummary = summarizeTurnSegments(lastTurn.segments);
86
+ }
82
87
  }
83
88
  const turns = completedTurnStates
84
89
  .map((turn) => ({
@@ -110,7 +110,6 @@ export const CursorAuthPlugin = async (input) => {
110
110
  async "chat.headers"(incoming, output) {
111
111
  if (incoming.model.providerID !== CURSOR_PROVIDER_ID)
112
112
  return;
113
- output.headers["x-opencode-session-id"] = incoming.sessionID;
114
113
  output.headers["x-session-id"] = incoming.sessionID;
115
114
  if (incoming.agent) {
116
115
  output.headers["x-opencode-agent"] = incoming.agent;
@@ -38,6 +38,8 @@ async function collectFullResponse(payload, accessToken, modelId, convKey, metad
38
38
  pendingExecs: [],
39
39
  outputTokens: 0,
40
40
  totalTokens: 0,
41
+ interactionToolArgsText: new Map(),
42
+ emittedToolCallIds: new Set(),
41
43
  };
42
44
  const tagFilter = createThinkingTagFilter();
43
45
  bridge.onData(createConnectFrameParser((messageBytes) => {
@@ -58,7 +60,17 @@ async function collectFullResponse(payload, accessToken, modelId, convKey, metad
58
60
  },
59
61
  });
60
62
  scheduleBridgeEnd(bridge);
61
- }, (checkpointBytes) => updateConversationCheckpoint(convKey, checkpointBytes), (info) => {
63
+ }, (checkpointBytes) => updateConversationCheckpoint(convKey, checkpointBytes), () => scheduleBridgeEnd(bridge), (info) => {
64
+ endStreamError = new Error(`Cursor returned unsupported ${info.category}: ${info.caseName}${info.detail ? ` (${info.detail})` : ""}`);
65
+ logPluginError("Closing non-streaming Cursor bridge after unsupported message", {
66
+ modelId,
67
+ convKey,
68
+ category: info.category,
69
+ caseName: info.caseName,
70
+ detail: info.detail,
71
+ });
72
+ scheduleBridgeEnd(bridge);
73
+ }, (info) => {
62
74
  endStreamError = new Error(`Cursor requested unsupported exec type: ${info.execCase}`);
63
75
  logPluginError("Closing non-streaming Cursor bridge after unsupported exec", {
64
76
  modelId,
@@ -27,6 +27,8 @@ function createBridgeStreamResponse(bridge, heartbeatTimer, blobStore, mcpTools,
27
27
  pendingExecs: [],
28
28
  outputTokens: 0,
29
29
  totalTokens: 0,
30
+ interactionToolArgsText: new Map(),
31
+ emittedToolCallIds: new Set(),
30
32
  };
31
33
  const tagFilter = createThinkingTagFilter();
32
34
  let assistantText = metadata.assistantSeedText ?? "";
@@ -47,6 +49,19 @@ function createBridgeStreamResponse(bridge, heartbeatTimer, blobStore, mcpTools,
47
49
  return;
48
50
  controller.enqueue(encoder.encode("data: [DONE]\n\n"));
49
51
  };
52
+ const failStream = (message, code) => {
53
+ if (closed)
54
+ return;
55
+ sendSSE({
56
+ error: {
57
+ message,
58
+ type: "server_error",
59
+ ...(code ? { code } : {}),
60
+ },
61
+ });
62
+ sendDone();
63
+ closeController();
64
+ };
50
65
  const closeController = () => {
51
66
  if (closed)
52
67
  return;
@@ -138,7 +153,18 @@ function createBridgeStreamResponse(bridge, heartbeatTimer, blobStore, mcpTools,
138
153
  sendSSE(makeChunk({}, "tool_calls"));
139
154
  sendDone();
140
155
  closeController();
141
- }, (checkpointBytes) => updateConversationCheckpoint(convKey, checkpointBytes), (info) => {
156
+ }, (checkpointBytes) => updateConversationCheckpoint(convKey, checkpointBytes), () => scheduleBridgeEnd(bridge), (info) => {
157
+ endStreamError = new Error(`Cursor returned unsupported ${info.category}: ${info.caseName}${info.detail ? ` (${info.detail})` : ""}`);
158
+ logPluginError("Closing Cursor bridge after unsupported message", {
159
+ modelId,
160
+ bridgeKey,
161
+ convKey,
162
+ category: info.category,
163
+ caseName: info.caseName,
164
+ detail: info.detail,
165
+ });
166
+ scheduleBridgeEnd(bridge);
167
+ }, (info) => {
142
168
  endStreamError = new Error(`Cursor requested unsupported exec type: ${info.execCase}`);
143
169
  logPluginError("Closing Cursor bridge after unsupported exec", {
144
170
  modelId,
@@ -187,10 +213,7 @@ function createBridgeStreamResponse(bridge, heartbeatTimer, blobStore, mcpTools,
187
213
  syncStoredBlobStore(convKey, blobStore);
188
214
  if (endStreamError) {
189
215
  activeBridges.delete(bridgeKey);
190
- if (!closed) {
191
- closed = true;
192
- controller.error(endStreamError);
193
- }
216
+ failStream(endStreamError.message, "cursor_bridge_closed");
194
217
  return;
195
218
  }
196
219
  if (!mcpExecReceived) {
@@ -210,11 +233,7 @@ function createBridgeStreamResponse(bridge, heartbeatTimer, blobStore, mcpTools,
210
233
  }
211
234
  activeBridges.delete(bridgeKey);
212
235
  if (code !== 0 && !closed) {
213
- sendSSE(makeChunk({ content: "\n[Error: bridge connection lost]" }));
214
- sendSSE(makeChunk({}, "stop"));
215
- sendSSE(makeUsageChunk());
216
- sendDone();
217
- closeController();
236
+ failStream("Cursor bridge connection lost", "cursor_bridge_closed");
218
237
  }
219
238
  });
220
239
  },
@@ -82,12 +82,13 @@ export function handleChatCompletion(body, accessToken, context = {}) {
82
82
  // Build the request. When tool results are present but the bridge died,
83
83
  // we must still include the last user text so Cursor has context.
84
84
  const mcpTools = buildMcpToolDefinitions(tools);
85
+ const hasPendingAssistantSummary = pendingAssistantSummary.trim().length > 0;
85
86
  const needsInitialHandoff = !stored.checkpoint &&
86
- (turns.length > 0 || pendingAssistantSummary || toolResults.length > 0);
87
+ (turns.length > 0 || hasPendingAssistantSummary || toolResults.length > 0);
87
88
  const replayTurns = needsInitialHandoff ? [] : turns;
88
89
  let effectiveUserText = needsInitialHandoff
89
90
  ? buildInitialHandoffPrompt(userText, turns, pendingAssistantSummary, toolResults)
90
- : toolResults.length > 0
91
+ : toolResults.length > 0 || hasPendingAssistantSummary
91
92
  ? buildToolResumePrompt(userText, pendingAssistantSummary, toolResults)
92
93
  : userText;
93
94
  const payload = buildCursorRequest(modelId, systemPrompt, effectiveUserText, replayTurns, stored.conversationId, stored.checkpoint, stored.blobStore);
@@ -3,3 +3,4 @@ export declare function buildCursorRequest(modelId: string, systemPrompt: string
3
3
  userText: string;
4
4
  assistantText: string;
5
5
  }>, conversationId: string, checkpoint: Uint8Array | null, existingBlobStore?: Map<string, Uint8Array>): CursorRequestPayload;
6
+ export declare function buildCursorResumeRequest(modelId: string, systemPrompt: string, conversationId: string, checkpoint: Uint8Array, existingBlobStore?: Map<string, Uint8Array>): CursorRequestPayload;
@@ -1,6 +1,6 @@
1
1
  import { create, fromBinary, toBinary } from "@bufbuild/protobuf";
2
2
  import { createHash } from "node:crypto";
3
- import { AgentClientMessageSchema, AgentRunRequestSchema, ConversationActionSchema, ConversationStateStructureSchema, ConversationStepSchema, AgentConversationTurnStructureSchema, ConversationTurnStructureSchema, AssistantMessageSchema, ModelDetailsSchema, UserMessageActionSchema, UserMessageSchema, } from "../proto/agent_pb";
3
+ import { AgentClientMessageSchema, AgentRunRequestSchema, ConversationActionSchema, ConversationStateStructureSchema, ConversationStepSchema, AgentConversationTurnStructureSchema, ConversationTurnStructureSchema, AssistantMessageSchema, ModelDetailsSchema, ResumeActionSchema, UserMessageActionSchema, UserMessageSchema, } from "../proto/agent_pb";
4
4
  export function buildCursorRequest(modelId, systemPrompt, userText, turns, conversationId, checkpoint, existingBlobStore) {
5
5
  const blobStore = new Map(existingBlobStore ?? []);
6
6
  // System prompt → blob store (Cursor requests it back via KV handshake)
@@ -64,6 +64,24 @@ export function buildCursorRequest(modelId, systemPrompt, userText, turns, conve
64
64
  value: create(UserMessageActionSchema, { userMessage }),
65
65
  },
66
66
  });
67
+ return buildRunRequest(modelId, conversationId, conversationState, action, blobStore);
68
+ }
69
+ export function buildCursorResumeRequest(modelId, systemPrompt, conversationId, checkpoint, existingBlobStore) {
70
+ const blobStore = new Map(existingBlobStore ?? []);
71
+ const systemJson = JSON.stringify({ role: "system", content: systemPrompt });
72
+ const systemBytes = new TextEncoder().encode(systemJson);
73
+ const systemBlobId = new Uint8Array(createHash("sha256").update(systemBytes).digest());
74
+ blobStore.set(Buffer.from(systemBlobId).toString("hex"), systemBytes);
75
+ const conversationState = fromBinary(ConversationStateStructureSchema, checkpoint);
76
+ const action = create(ConversationActionSchema, {
77
+ action: {
78
+ case: "resumeAction",
79
+ value: create(ResumeActionSchema, {}),
80
+ },
81
+ });
82
+ return buildRunRequest(modelId, conversationId, conversationState, action, blobStore);
83
+ }
84
+ function buildRunRequest(modelId, conversationId, conversationState, action, blobStore) {
67
85
  const modelDetails = create(ModelDetailsSchema, {
68
86
  modelId,
69
87
  displayModelId: modelId,
@@ -1,4 +1,4 @@
1
- import { errorDetails, logPluginError } from "../logger";
1
+ import { errorDetails, logPluginError, logPluginWarn } from "../logger";
2
2
  import { handleChatCompletion } from "./chat-completion";
3
3
  import { activeBridges, conversationStates } from "./conversation-state";
4
4
  let proxyServer;
@@ -42,14 +42,32 @@ export async function startProxy(getAccessToken, models = []) {
42
42
  throw new Error("Cursor proxy access token provider not configured");
43
43
  }
44
44
  const accessToken = await proxyAccessTokenProvider();
45
- const sessionId = req.headers.get("x-opencode-session-id") ??
46
- req.headers.get("x-session-id") ??
47
- undefined;
45
+ const sessionId = req.headers.get("x-session-id") ?? undefined;
48
46
  const agentKey = req.headers.get("x-opencode-agent") ?? undefined;
49
- return handleChatCompletion(body, accessToken, {
47
+ const response = await handleChatCompletion(body, accessToken, {
50
48
  sessionId,
51
49
  agentKey,
52
50
  });
51
+ if (response.status >= 400) {
52
+ let responseBody = "";
53
+ try {
54
+ responseBody = await response.clone().text();
55
+ }
56
+ catch (error) {
57
+ responseBody = `Failed to read rejected response body: ${error instanceof Error ? error.message : String(error)}`;
58
+ }
59
+ logPluginWarn("Rejected Cursor chat completion", {
60
+ path: url.pathname,
61
+ method: req.method,
62
+ sessionId,
63
+ agentKey,
64
+ status: response.status,
65
+ requestBody: body,
66
+ requestBodyText: JSON.stringify(body),
67
+ responseBody,
68
+ });
69
+ }
70
+ return response;
53
71
  }
54
72
  catch (err) {
55
73
  const message = err instanceof Error ? err.message : String(err);
@@ -7,6 +7,11 @@ export interface UnhandledExecInfo {
7
7
  execId: string;
8
8
  execMsgId: number;
9
9
  }
10
+ export interface UnsupportedServerMessageInfo {
11
+ category: "agentMessage" | "interactionUpdate" | "interactionQuery" | "execServerControl" | "toolCall";
12
+ caseName: string;
13
+ detail?: string;
14
+ }
10
15
  export declare function parseConnectEndStream(data: Uint8Array): Error | null;
11
16
  export declare function makeHeartbeatBytes(): Uint8Array;
12
17
  export declare function scheduleBridgeEnd(bridge: CursorSession): void;
@@ -34,4 +39,4 @@ export declare function computeUsage(state: StreamState): {
34
39
  completion_tokens: number;
35
40
  total_tokens: number;
36
41
  };
37
- export declare function processServerMessage(msg: AgentServerMessage, blobStore: Map<string, Uint8Array>, mcpTools: McpToolDefinition[], sendFrame: (data: Uint8Array) => void, state: StreamState, onText: (text: string, isThinking?: boolean) => void, onMcpExec: (exec: PendingExec) => void, onCheckpoint?: (checkpointBytes: Uint8Array) => void, onUnhandledExec?: (info: UnhandledExecInfo) => void): void;
42
+ export declare function processServerMessage(msg: AgentServerMessage, blobStore: Map<string, Uint8Array>, mcpTools: McpToolDefinition[], sendFrame: (data: Uint8Array) => void, state: StreamState, onText: (text: string, isThinking?: boolean) => void, onMcpExec: (exec: PendingExec) => void, onCheckpoint?: (checkpointBytes: Uint8Array) => void, onTurnEnded?: () => void, onUnsupportedMessage?: (info: UnsupportedServerMessageInfo) => void, onUnhandledExec?: (info: UnhandledExecInfo) => void): void;
@@ -128,10 +128,10 @@ export function computeUsage(state) {
128
128
  const prompt_tokens = Math.max(0, total_tokens - completion_tokens);
129
129
  return { prompt_tokens, completion_tokens, total_tokens };
130
130
  }
131
- export function processServerMessage(msg, blobStore, mcpTools, sendFrame, state, onText, onMcpExec, onCheckpoint, onUnhandledExec) {
131
+ export function processServerMessage(msg, blobStore, mcpTools, sendFrame, state, onText, onMcpExec, onCheckpoint, onTurnEnded, onUnsupportedMessage, onUnhandledExec) {
132
132
  const msgCase = msg.message.case;
133
133
  if (msgCase === "interactionUpdate") {
134
- handleInteractionUpdate(msg.message.value, state, onText);
134
+ handleInteractionUpdate(msg.message.value, state, onText, onMcpExec, onTurnEnded, onUnsupportedMessage);
135
135
  }
136
136
  else if (msgCase === "kvServerMessage") {
137
137
  handleKvMessage(msg.message.value, blobStore, sendFrame);
@@ -139,6 +139,18 @@ export function processServerMessage(msg, blobStore, mcpTools, sendFrame, state,
139
139
  else if (msgCase === "execServerMessage") {
140
140
  handleExecMessage(msg.message.value, mcpTools, sendFrame, onMcpExec, onUnhandledExec);
141
141
  }
142
+ else if (msgCase === "execServerControlMessage") {
143
+ onUnsupportedMessage?.({
144
+ category: "execServerControl",
145
+ caseName: msg.message.value.message.case ?? "undefined",
146
+ });
147
+ }
148
+ else if (msgCase === "interactionQuery") {
149
+ onUnsupportedMessage?.({
150
+ category: "interactionQuery",
151
+ caseName: msg.message.value.query.case ?? "undefined",
152
+ });
153
+ }
142
154
  else if (msgCase === "conversationCheckpointUpdate") {
143
155
  const stateStructure = msg.message.value;
144
156
  if (stateStructure.tokenDetails) {
@@ -148,8 +160,14 @@ export function processServerMessage(msg, blobStore, mcpTools, sendFrame, state,
148
160
  onCheckpoint(toBinary(ConversationStateStructureSchema, stateStructure));
149
161
  }
150
162
  }
163
+ else {
164
+ onUnsupportedMessage?.({
165
+ category: "agentMessage",
166
+ caseName: msgCase ?? "undefined",
167
+ });
168
+ }
151
169
  }
152
- function handleInteractionUpdate(update, state, onText) {
170
+ function handleInteractionUpdate(update, state, onText, onMcpExec, onTurnEnded, onUnsupportedMessage) {
153
171
  const updateCase = update.message?.case;
154
172
  if (updateCase === "textDelta") {
155
173
  const delta = update.message.value.text || "";
@@ -164,9 +182,75 @@ function handleInteractionUpdate(update, state, onText) {
164
182
  else if (updateCase === "tokenDelta") {
165
183
  state.outputTokens += update.message.value.tokens ?? 0;
166
184
  }
167
- // toolCallStarted, partialToolCall, toolCallDelta, toolCallCompleted
168
- // are intentionally ignored. MCP tool calls flow through the exec
169
- // message path (mcpArgs mcpResult), not interaction updates.
185
+ else if (updateCase === "partialToolCall") {
186
+ const partial = update.message.value;
187
+ if (partial.callId && partial.argsTextDelta) {
188
+ state.interactionToolArgsText.set(partial.callId, partial.argsTextDelta);
189
+ }
190
+ }
191
+ else if (updateCase === "toolCallCompleted") {
192
+ const exec = decodeInteractionToolCall(update.message.value, state);
193
+ if (exec)
194
+ onMcpExec(exec);
195
+ }
196
+ else if (updateCase === "turnEnded") {
197
+ onTurnEnded?.();
198
+ }
199
+ else if (updateCase === "toolCallStarted" ||
200
+ updateCase === "toolCallDelta" ||
201
+ updateCase === "thinkingCompleted" ||
202
+ updateCase === "userMessageAppended" ||
203
+ updateCase === "summary" ||
204
+ updateCase === "summaryStarted" ||
205
+ updateCase === "summaryCompleted" ||
206
+ updateCase === "heartbeat" ||
207
+ updateCase === "stepStarted" ||
208
+ updateCase === "stepCompleted") {
209
+ return;
210
+ }
211
+ else {
212
+ onUnsupportedMessage?.({
213
+ category: "interactionUpdate",
214
+ caseName: updateCase ?? "undefined",
215
+ });
216
+ }
217
+ // toolCallStarted, partialToolCall, toolCallDelta, and non-MCP
218
+ // toolCallCompleted updates are informational only. Actionable MCP tool
219
+ // calls may still appear here on some models, so we surface those, but we
220
+ // do not abort the bridge for native Cursor tool-call progress events.
221
+ }
222
+ function decodeInteractionToolCall(update, state) {
223
+ const callId = update.callId ?? "";
224
+ const toolCase = update.toolCall?.tool?.case;
225
+ if (toolCase !== "mcpToolCall")
226
+ return null;
227
+ const mcpArgs = update.toolCall?.tool?.value?.args;
228
+ if (!mcpArgs)
229
+ return null;
230
+ const toolCallId = mcpArgs.toolCallId || callId || crypto.randomUUID();
231
+ if (state.emittedToolCallIds.has(toolCallId))
232
+ return null;
233
+ const decodedMap = decodeMcpArgsMap(mcpArgs.args ?? {});
234
+ const partialArgsText = callId
235
+ ? state.interactionToolArgsText.get(callId)?.trim()
236
+ : undefined;
237
+ let decodedArgs = "{}";
238
+ if (Object.keys(decodedMap).length > 0) {
239
+ decodedArgs = JSON.stringify(decodedMap);
240
+ }
241
+ else if (partialArgsText) {
242
+ decodedArgs = partialArgsText;
243
+ }
244
+ state.emittedToolCallIds.add(toolCallId);
245
+ if (callId)
246
+ state.interactionToolArgsText.delete(callId);
247
+ return {
248
+ execId: callId || toolCallId,
249
+ execMsgId: 0,
250
+ toolCallId,
251
+ toolName: mcpArgs.toolName || mcpArgs.name || "unknown_mcp_tool",
252
+ decodedArgs,
253
+ };
170
254
  }
171
255
  /** Send a KV client response back to Cursor. */
172
256
  function sendKvResponse(kvMsg, messageCase, value, sendFrame) {
@@ -4,4 +4,6 @@ export interface StreamState {
4
4
  pendingExecs: PendingExec[];
5
5
  outputTokens: number;
6
6
  totalTokens: number;
7
+ interactionToolArgsText: Map<string, string>;
8
+ emittedToolCallIds: Set<string>;
7
9
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@playwo/opencode-cursor-oauth",
3
- "version": "0.0.0-dev.2c48be2f48c9",
3
+ "version": "0.0.0-dev.4258a6733133",
4
4
  "description": "OpenCode plugin that connects Cursor's API to OpenCode via OAuth, model discovery, and a local OpenAI-compatible proxy.",
5
5
  "license": "MIT",
6
6
  "type": "module",