Repository navigation
feat(agent)!: reject requests that arrive before initialize - #162
Conversation
The spec gives -32002 (Resource not found) to a request that names a session or file that does not exist, with data.sessionId for an unknown session. errors.go had a constructor for every other ErrorCode in the schema. A test now pins each constructor to the schema's ErrorCode code and title, and fails when the schema gains a code without one. _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
The spec says an agent SHOULD answer a request other than initialize that arrives before initialization completes with -32600. AgentSideConnection passed every request and notification to the Agent. Until the Agent's Initialize returns without an error, it now answers every other request, _ extension requests included, with -32600 and drops every notification. A failed initialize leaves the connection uninitialized. NewConnection starts reading before it returns, so a handler could read a.conn before NewAgentSideConnection stored it (registerPrompt on main does too). Handlers now wait on a ready channel that the constructor closes once a.conn is set, as the proxy's handleWhenReady does. Tests that skipped initialize now send it first. MIGRATION_v0.21.md, the README and doc.go describe the gate, and the verify-session-cancel fingerprint is re-synced. BREAKING CHANGE: AgentSideConnection answers a request other than initialize with -32600, and drops a notification, until the Agent's Initialize returns without an error. _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
The example agent now returns agentInfo, answers a session it does not know (prompt, set_mode, set_config_option, load) with NewResourceNotFound and data.sessionId, and rejects a session/list cursor it never issued and an unknown mode with -32602. The G3 session-delete journey and its feature doc expect -32002 for a prompt on a deleted session. _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 89409f3ad7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if err == nil { | ||
| a.initialized.Store(true) |
There was a problem hiding this comment.
Mark initialized only after encoding the success response
When Initialize returns a response containing an unencodable value, such as malformed json.RawMessage in InitializeResponse.Meta, a.handle reports no error so this flag becomes true, but Connection.handleInbound subsequently fails to marshal the response and sends the client -32603. The client therefore observes a failed initialization while subsequent requests such as session/new pass the gate and reach the agent; keep the connection uninitialized until the successful response has at least been encoded.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3a1481c: the gate now encodes the initialize response itself and stays closed when encoding fails, so the client's -32603 and the gate agree. TestAgentSideConnection_InitializeThatDoesNotEncodeKeepsTheGate covers it, and fails without the fix.
An Initialize response that json.Marshal rejects, such as a Meta value holding invalid raw JSON, reaches the client as -32603, but the gate opened anyway, so later requests reached the Agent after an initialize the client saw fail. The gate now encodes the response itself and stays closed when that fails. _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3a1481c045
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if !a.initialized.Load() { | ||
| return a.handleBeforeInitialize(ctx, method, params) |
There was a problem hiding this comment.
Reject messages that arrived before initialization
When input is buffered or handlers are delayed by scheduling, the concurrent initialize handler can set initialized before an earlier request or notification reaches this load, so that earlier message bypasses the gate and reaches the agent. This is reproducible with the added TestAgentSideConnection_HandlesMessagesWaitingAtConstruction under go test -race -count=10, where the session/cancel preceding initialize is delivered; enforce the gate using message arrival order rather than the flag's value when the handler happens to run.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 23fb821: the connection records the arrival number of the initialize that opened it, and a message passes the gate only if it arrived after that one. TestAgentSideConnection_GateKeysOnArrivalOrder runs handlers out of arrival order and fails with the flag-only gate.
…alize Request handlers run concurrently, so an initialize could finish before the handler of a message that arrived ahead of it checked the gate, and that message reached the Agent. The connection now records the arrival number of the initialize that opened it, and a message passes the gate only if it arrived after that one. The verify-session-cancel fingerprint is re-synced. _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 23fb821372
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| at := a.openedAt.Load() | ||
| return at != 0 && a.arrivalOf(ctx) >= at |
There was a problem hiding this comment.
Keep pipelined messages behind initialization completion
When a client writes initialize and another request back-to-back, the second message can arrive while Initialize is still running but have its handler scheduled only after openedAt is set. This comparison then admits it because its arrival number is greater than the initialize request's, even though it arrived before initialization completed, so it reaches the Agent instead of receiving the documented -32600. Track whether each message arrived after successful completion rather than only after the initialize request's arrival.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this one. The gate holds back every message that arrived before the initialize that opened the connection. A message pipelined after initialize can still get through when its handler starts after initialize returned. The docs say so: a client sends other requests only after the initialize reply, and no client here pipelines. Rejecting by completion time would need the arrival count at the moment initialize finishes. Only the read loop touches that counter, so it would take a new atomic in connection.go and a remap of the notification-barrier skill's line citations, all for a SHOULD.
|
Pre-merge verification of 23fb821: PASS+NOTES I ran these checks on a detached worktree of 23fb821 against base 04d1252:
Notes (none blocks the merge):
Generated with |
Why
A run of the ACP Test Compatibility Kit (acp-tck v0.5.0) against
example/agentfound two gaps in the SDK.AgentSideConnectionpasses requests to the Agent beforeinitialize, where the spec says an agent SHOULD answer them with-32600. Anderrors.gohas no constructor for-32002(Resource not found), the code the spec gives an unknown session. The TCK gate that checks both is the next PR in this stack.What changed
NewResourceNotFound(-32002). A test pins everyNew*constructor to the schema'sErrorCodecode and title, and fails when the schema gains a code that has no constructor.Initializereturns without an error,AgentSideConnectionanswers every other request,_extension requests included, with-32600and drops every notification. A failedinitializeleaves the connection uninitialized.$/cancel_requestis still handled by the read loop.NewConnectionstarts reading before it returns, so a handler could reada.connbeforeNewAgentSideConnectionstored it. This race is on main too, inregisterPrompt. Handlers now wait on areadychannel, as the proxy'shandleWhenReadydoes.example/agentsendsagentInfo, answers an unknown session with-32002anddata.sessionId, and rejects an unissuedsession/listcursor and an unknown mode with-32602.MIGRATION_v0.21.mdsection, plus the README anddoc.go. The G3session-deletejourney expects-32002. The verify-session-cancel fingerprint is re-synced.Scope
The agent side only.
ClientSideConnectionand the proxy do not change. The tests that used to skipinitializenow send it first, and none of them lost an assertion.Tradeoffs
session/newwithout waiting for theinitializereply can get-32600. Every client in this repo waits.agent.goinstead of splittingconnection.go. Splitting would shift the line citations of both TLA+ gates. fix: start reading only after the side connection stores conn #84 is an open PR that takes theconnection.goroute.Blast Radius
Agents built on the SDK whose clients send messages before
initializecompletes.Verification
make test, andgo test -race -count=3 .and./example/....-racewithout thereadywait.example/agent: ACP-ERROR-003, ACP-ERROR-004, ACP-ERROR-005, ACP-INIT-004 and ACP-LIST-003 go from FAIL to PASS, and nothing else changes.Generated with
xum• Model:anthropic:claude-opus-5-5• Thinking:high