anthropics / anthropics/claude-agent-sdk-typescript

Rv writes user message without awaiting A.initialization, causing stdin race at CLI

Abierto
#286 0 comentarios 0 reacciones 0 asignados Ver en GitHub
bug
Lenguaje dominante
Shell
Estrellas
1.8k
Forks
226
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

### What breaks

The SDK writes the `initialize` control_request and the first user message to the CLI's stdin with no await between them. The CLI's `initialize` handler is what populates the SDK MCP server map. When the CLI starts processing the user message before it drains the `initialize` message, the first `messages.create` is sent without the SDK MCP tools. That makes `tools[]` differ between Turn 1 and Turn 2, which breaks Anthropic's prompt cache on Turn 2.

On workloads where cache read should approach 100%, we saw it drop to around 82%.

### Versions

- `@anthropic-ai/claude-agent-sdk-typescript`: 0.2.108
- Reproduced against `@anthropic-ai/claude-code` 2.1.77 and 2.1.110

### Location

In `assistant.mjs`, the `Rv` function (around byte 1,207,734 of the minified file) writes the user message to the CLI's stdin. The SDK already has an `A.initialization` promise that resolves on the CLI's `initialize` control_response. `Rv` does not wait for it.

### Proposed fix

One line inside `Rv`:

```js
async function Rv(A, Q, B, I) {
await A.initialization; // <-- add this line
// ... existing body
}
```

The promise exists. It resolves when the CLI acks the initialize. `Rv` just needs to await it before writing the user payload.

### Caveat

In our testing this one-line fix passed 9/13 back-to-back runs, while a CLI-side gate that waits for the same signal passed 10/10. So there is probably a second race we have not traced. That said, writing the user message before the CLI has acked init is a weird invariant to live with on its own, and this fix is the one-liner in the right place. Worth taking even if a residual race turns up later.

### Related issues

- #89 (closest existing discussion of MCP tool ordering breaking cache)
- #274 (related initialize-ack semantics)
- Companion issue on the CLI side: anthropics/claude-code#49753

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Evaluación

Este issue todavía no se ha evaluado.

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.