Skip to content

Commit fdf1d0a

Browse files
committed
merge dev into fix/issue-1992-cursor-prompt-injection
2 parents 19afd9e + 314f3ed commit fdf1d0a

49 files changed

Lines changed: 6010 additions & 24 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎devlog/_plan/260817_cursor_toolcall_decode/000_index.md‎

Lines changed: 305 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# 001 — Tool-call lifecycle decode
2+
3+
Source: `src/adapters/cursor/protobuf-events.ts`. Verified by direct read plus
4+
an independent `gpt-5.6-sol` audit, then corrected after an adversarial audit.
5+
6+
## The lifecycle
7+
8+
Cursor delivers a client tool call across several interaction updates, and the
9+
adapter deliberately does **not** mirror them one-to-one downstream:
10+
11+
| Cursor update | Adapter action | Emitted downstream |
12+
|---------------|----------------|--------------------|
13+
| `toolCallStarted` (`:1249`) | `recordToolCall` opens the call | **nothing** (deferred) |
14+
| `partialToolCall` (`:1254`) | `recordToolCall` if new, then `bufferToolArgs` on `argsTextDelta` | nothing |
15+
| `toolCallDelta` (`:1265`) | **nothing** — returns `[]` | nothing |
16+
| `toolCallCompleted` (`:1269`) | `resolveCompletedArgs` + `commitToolCall` | `tool_call_start` -> `tool_call_delta` -> `tool_call_end` |
17+
18+
**Correction (adversarial audit).** An earlier draft put argument buffering on
19+
`toolCallDelta`. That branch returns `[]` by design: Cursor's typed deltas cover
20+
native exec internals (shell/task/edit), while client Responses tools return as
21+
`McpToolCall` plus partial args text. Buffering happens on `partialToolCall`,
22+
which the original table omitted entirely.
23+
24+
The deferral is intentional and correct: Cursor can open several calls in
25+
parallel or interleave their arg streams, while the Codex bridge tracks a single
26+
current call. Emitting each completed call as one atomic unit serializes them
27+
safely. The cost is that an **incomplete** call has emitted nothing at all, which
28+
is what makes F1 (see `003`) invisible rather than merely wrong.
29+
30+
## Argument resolution
31+
32+
`resolveCompletedArgs` (`:354`) picks in order:
33+
34+
1. the structured protobuf map when it has bytes (canonical, schema-normalized);
35+
2. otherwise buffered streamed text, normalized when it is complete JSON;
36+
3. otherwise the buffered text **verbatim**.
37+
38+
Case 3 is deliberate: passing malformed text through lets the bridge reject it
39+
(`bridge.ts:1070`) instead of silently converting truncated args into `{}` and
40+
executing a tool with the wrong arguments. `argsTextDelta` is cumulative, so the
41+
buffer keeps the longest value seen rather than concatenating.
42+
43+
## Error surfaces
44+
45+
`recordToolCall` returns an error for an un-advertised tool name (`:1103`) and
46+
for exceeding `maxClientToolCalls` (`:1107`). `commitToolCall` returns an error
47+
only for invalid freeform args (`:1160`) and invalid shell-bridge args (`:1163`).
48+
A failed structured-edit conversion deliberately returns **text**, not an error
49+
(`:1175`), keeping the turn alive.
50+
51+
Every `error` `CursorServerMessage` is turn-fatal downstream: it maps to
52+
`AdapterEvent.error` (`message-mapper.ts:28`) and then `response.failed`
53+
(`bridge.ts:1219`).
54+
55+
## Verdict
56+
57+
The lifecycle itself is sound. Two prior hypotheses were disproved here (see
58+
`000`), and no change to this file is proposed for its own sake — `010` does not
59+
modify it at all in the revised plan.
60+
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# 002 — Tool-result encoding decode
2+
3+
Source: `src/adapters/cursor/protobuf-request.ts`, `gen/agent_pb.ts`,
4+
`native-exec-mcp.ts`. Verified by direct read plus an independent
5+
`gpt-5.6-sol` audit.
6+
7+
## F2 — images are destroyed, and the wire did not ask for that (High)
8+
9+
`contentToText` (`protobuf-request.ts:328`) maps every non-text part of a tool
10+
result to a literal placeholder:
11+
12+
```ts
13+
.map(part => part.type === "text" ? part.text : `[image input unsupported by Cursor adapter phase 3: ${part.detail ?? "auto"}]`)
14+
```
15+
16+
`toolResultPart` (`:384`) then always builds exactly one `text` content item. So
17+
a screenshot returned by Computer Use, a browser QA tool, or any image-returning
18+
MCP tool reaches Cursor as the string
19+
`[image input unsupported by Cursor adapter phase 3: auto]` and nothing else.
20+
21+
**The Cursor protobuf supports images.** `McpToolResultContentItem.content` is a
22+
oneof with exactly two defined cases (`gen/agent_pb.ts:8476`):
23+
24+
```ts
25+
content:
26+
| { value: McpTextContent; case: "text" } // field 1
27+
| { value: McpImageContent; case: "image" } // field 2
28+
| { case: undefined; value?: undefined };
29+
```
30+
31+
`McpImageContent` (`:8449`) carries `data: Uint8Array` (bytes, base64 in JSON)
32+
and `mimeType: string`.
33+
34+
**The adapter already knows how to send one.** `native-exec-mcp.ts:115` decodes
35+
base64 from an MCP block and emits a real `McpImageContent`. That path covers
36+
tools invoked through `CursorMcpManager`; it does not cover Codex
37+
`OcxToolResultMessage` values flowing through `protobuf-request.ts`. The
38+
placeholder is therefore not a wire limitation but an unfinished migration — the
39+
"phase 3" in its own text.
40+
41+
A model driving Computer Use therefore receives a blind result and cannot see
42+
what its own action did. That is a real capability loss, proven by source
43+
reading.
44+
45+
**It is not proven to be the cause of the reported retries and session resets.**
46+
No live trace ties those symptoms to this branch, and the external evidence in
47+
`004` points at least partly elsewhere (the `node_repl` runtime). An adversarial
48+
audit flagged the original causal claim as unsupported; it is withdrawn. The
49+
defect stands on its own merits and does not need to explain every symptom to be
50+
worth fixing.
51+
52+
## The three result paths in `conversationTurns`
53+
54+
| Path | Behavior | Lines |
55+
|------|----------|-------|
56+
| External model | `AssistantMessage` with `[Tool Result]`/`[Tool Error]` + placeholder | 481-490 |
57+
| Native model, matching pending call | `toolResultPart(result)` attached to the MCP call — still text-only | 493-496 |
58+
| Native model, no matching call | `toolResultToText` as an `AssistantMessage` | 498-503 |
59+
60+
All three lose the image. A fix must cover the native path (real
61+
`McpImageContent`) and degrade honestly on the external path.
62+
63+
## Other image surfaces (context, not in scope)
64+
65+
User-message images are also placeholdered, at `request-builder.ts:201` and
66+
`protobuf-request.ts:314`. The schema would support them: `UserMessage` has
67+
`selectedContext` -> `selectedImages` (`agent_pb.ts:1823`, `:11178`), and
68+
`SelectedImage` accepts `blobId`, inline `data`, or `blobIdWithData`
69+
(`:10389`). No adapter code populates these. Out of scope for this unit; noted
70+
so a later unit does not have to rediscover it.
71+
72+
## Size limits (hypothesis partly disproved)
73+
74+
There is no single whole-request cap and no cap inside `contentToText`. What
75+
exists:
76+
77+
- tool catalog: 330 tools / 120,000 protobuf bytes (`request-builder.ts:29`) —
78+
definitions only, not results;
79+
- external root replay: 192 roots / 512 KiB with UTF-8 truncation marked
80+
`…[truncated for Cursor external replay budget]` (`protobuf-request.ts:60`, `:122`);
81+
- blob store: 16 MiB per blob, 4,096 entries, 64 MiB total, 15-minute TTL
82+
(`native-exec.ts:81`);
83+
- `requestScope` pins blobs for the in-flight request so eviction cannot
84+
invalidate advertised ids; over-capacity raises `CursorBlobAdmissionError`
85+
rather than truncating (`native-exec.ts:363`, `:374`).
86+
87+
Implication for `020`: adding real image bytes to results makes the blob and
88+
replay budgets load-bearing, so the fix must bound image payloads deliberately
89+
instead of trusting these limits to absorb them.
90+
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# 003 — Transport terminal decode
2+
3+
Source: `src/adapters/cursor/live-transport.ts`, `transport-retry.ts`,
4+
`src/bridge.ts`. Verified by direct read plus an independent `gpt-5.6-sol`
5+
audit that returned FAIL on this surface.
6+
7+
## Terminal settlement paths
8+
9+
`createTerminalSettler()` (`live-transport.ts:102`) is single-shot: the first
10+
settle wins, later ones are ignored.
11+
12+
| Event | Classification |
13+
|-------|----------------|
14+
| Connect end-stream frame with error or malformed payload | fatal (`:891`, `:900`) |
15+
| Successful `{}` trailer | **no settlement**; waits for HTTP/2 `end` (`:175`) |
16+
| Nonzero `grpc-status` trailer | fatal (`:970`) |
17+
| HTTP/2 `end` with leftover frame bytes | fatal `ConnectFrameError` **unless `expectedClose`** (`:1016`) |
18+
| HTTP/2 `end` with zero frames | fatal unexpected EOF **unless `expectedClose`** (`:1024`) |
19+
| HTTP/2 `end` with >=1 complete frame | **unconditional graceful finish** (`:1029`) |
20+
| Socket/session error | fatal via `failAndClear` (`:824`, `:975`) |
21+
| Socket error after intentional client-tool suspension | graceful, `expectedClose` (`:806`) |
22+
| Abort | fatal unless `expectedClose` or already settled (`:1036`) |
23+
| First-frame timeout (30s default, `:88`) | fatal (`:835`) |
24+
25+
A fatal settlement makes `run()` throw (`:619`); a graceful settlement only
26+
marks the iterator done (`:597`).
27+
28+
## F1 — the clean-EOF gap (High)
29+
30+
The last row of that table is the defect. The `end` handler drains queued frame
31+
work, then classifies: leftover bytes -> fail, zero frames -> fail, otherwise
32+
`settler.settleFinish()` — **without consulting `state.terminated`, and without
33+
asking whether the application-level `turnEnded` frame ever arrived**.
34+
35+
Consequences when Cursor's stream ends cleanly mid-turn:
36+
37+
1. `finalizeTurnEvents` never runs, so the fail-closed open-tool-call check at
38+
`protobuf-events.ts:1361` — the code written for exactly this hazard — is
39+
bypassed.
40+
2. The adapter emits neither `done` nor `error`. Only pre-EOF text/reasoning
41+
reached the bridge; the tool call was buffered and deferred, so it is simply
42+
gone (`protobuf-events.ts:1249`).
43+
3. Streaming Responses partly repairs this: a terminal-less adapter EOF becomes
44+
`response.incomplete` with reason `adapter_eof` (`bridge.ts:1283`).
45+
4. **Non-streaming does not.** With no error and no incomplete event, status
46+
defaults to `"completed"` (`bridge.ts:1829`), so a truncated turn is reported
47+
as a success.
48+
49+
This matches the external report of a `cursor-grok` stream ending with
50+
`hasToolCalls: true` and partial content before `turnEnded` (see `004`).
51+
52+
## Retry behavior
53+
54+
The retry guard (`transport-retry.ts:99`) is correct and must not be loosened:
55+
56+
```ts
57+
const canRetry =
58+
!emittedAny &&
59+
attempt < CURSOR_RETRY_ATTEMPTS - 1 &&
60+
!signal?.aborted &&
61+
requestUncommitted(transport) &&
62+
isRetryableCursorError(err);
63+
```
64+
65+
`emittedAny` is set before `onEvent()` (`:93`), so any emitted event blocks
66+
retry — replay after partial emission would duplicate output. Note the second-
67+
order consequence of F1: a clean EOF **throws nothing**, so the retry wrapper
68+
returns success and never evaluates the guard at all (`:97`). Fixing F1 to
69+
throw a typed error is what makes this path reachable in the first place.
70+
71+
## Idle and keep-alive
72+
73+
- First-frame deadline 30s (`:88`), cleared by the first raw `data` chunk (`:940`).
74+
- No post-first-frame idle timeout in the transport.
75+
- `clientHeartbeat` written upstream every 5s (`:1042`).
76+
- The Responses bridge has a separate ~300s silence watchdog (`bridge.ts:1321`).
77+
78+
For a Responses-owned Computer Use call the transport normally emits `done` and
79+
cancels Cursor before the client runs the minutes-long tool (`:737`), so tool
80+
duration should not idle that stream. An inline native execution, or a call left
81+
open awaiting completion, can still hit the 300s watchdog while 5s heartbeats
82+
keep the socket alive — the socket is healthy and the turn is dead, which is the
83+
worst shape for diagnosis.
84+
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# 004 — External wire and format evidence
2+
3+
Gathered by a five-lane `gpt-5.6-luna` discovery swarm, then filtered here.
4+
Public reverse-engineering of Cursor's protocol is **lead-grade, not primary**:
5+
the repository's own generated `gen/agent_pb.ts` outranks all of it and is what
6+
`002` relies on. These sources matter for behavior we cannot read from our tree.
7+
8+
## Load-bearing
9+
10+
**A cursor-grok stream is reported to end before `turnEnded` with tool calls in
11+
flight.** A 2026-07-27 report for `cursor-grok-4.5-high` records
12+
`hasToolCalls: true`, partial content, and "Cursor stream ended before
13+
turnEnded", requiring manual continuation — attributed to the HTTP/2 stream
14+
ending without the application-level frame.
15+
<https://github.com/can1357/oh-my-pi/issues/6772> (lead)
16+
17+
This is independent corroboration that F1 is a real upstream behavior and not a
18+
theoretical branch. It is the reason `010` treats clean EOF as a first-class
19+
terminal state rather than an edge case.
20+
21+
**Cursor documents that MCP tool responses can return base64 images.**
22+
<https://docs.cursor.com/context/model-context-protocol> (primary for product
23+
behavior). Combined with `McpImageContent` in our generated schema, image
24+
results are supported end to end, which is what makes `020` a passthrough fix
25+
rather than a feature request.
26+
27+
**MCP specifies images in tool results.** `CallToolResult.content` is a
28+
`ContentBlock[]` whose union includes `ImageContent` with base64 `data` and
29+
`mimeType`. <https://modelcontextprotocol.io/specification/2025-11-25/schema> (primary)
30+
31+
**Naive gateway translation of image tool results fails loudly.** LiteLLM passed
32+
Chat-Completions-style `image_url` content into a Responses `function_call_output`
33+
and OpenAI rejected it, because Responses expects `input_image`.
34+
<https://github.com/BerriAI/litellm/issues/17507> (lead). Design consequence for
35+
`020`: emit the upstream's own image representation, never a foreign one.
36+
37+
**Bun reuses stale pooled keep-alive sockets without liveness checks**, so a
38+
reaped connection hangs until Bun's ceiling instead of reconnecting.
39+
<https://github.com/oven-sh/bun/issues/31894> (primary, closed "not planned").
40+
Relevant to long-lived Cursor streams; not itself proven to be our defect.
41+
42+
## Context only
43+
44+
- **Protocol principle, adjacent transport.** In gRPC over HTTP/2, status
45+
trailers are required for normal completion, and Connect's gRPC-web transport
46+
fails loudly when the encoded trailer is missing.
47+
<https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md> (primary),
48+
<https://github.com/connectrpc/connect-es/issues/1115> (primary).
49+
**Terminology caution:** this adapter speaks Connect framing with an encoded
50+
end-stream envelope (`live-transport.ts:787-900`), not gRPC-web trailers, so
51+
these sources supply the general principle — a body without its terminal is not
52+
authoritative success — and not a statement about our exact wire. F1 rests on
53+
source reading (`003`), not on these citations.
54+
- xAI documents Grok 4.6 tool calling over streaming and synchronous modes.
55+
<https://docs.x.ai/developers/tools/streaming-and-sync> (primary). No official
56+
changelog naming grok-4.6 as dropping tool calls was found.
57+
- A Grok-compatible path was reported returning empty `arguments` with the real
58+
JSON in `partialJson`. <https://github.com/earendil-works/pi/issues/3131> (lead).
59+
- Codex Computer Use is bridged through the `node_repl` runtime; several 2026
60+
reports describe it being detected but unattached, with kernel resets.
61+
<https://github.com/openai/codex/issues/21530> (lead). Some of the user's
62+
observed instability may originate here rather than in our adapter — recorded
63+
so we do not over-attribute every symptom to the Cursor path.
64+
65+
## Negative result
66+
67+
No public authoritative `.proto` confirming `McpSuccess` or
68+
`McpToolResultContentItem` was found; available dumps use older
69+
`ClientSideToolV2Call` terminology or are explicitly speculative. Our generated
70+
schema remains the only trustworthy source, which is why `002` quotes it directly.
71+

0 commit comments

Comments
 (0)