fix(acp): send available commands after the session response (#52522)

This commit is contained in:
Shoubhit Dash
2026-10-01 21:42:35 +05:30
committed by GitHub
Unverified
parent 48f3c2e923
commit 08c15ec1cd
6 changed files with 203 additions and 47 deletions
+10 -4
View File
@@ -6,6 +6,7 @@ import {
type AgentNotificationMethod,
type AgentRequestHandlersByMethod,
type AgentRequestMethod,
type JsonRpcId,
type Stream,
} from "@agentclientprotocol/sdk"
import type { OpenCodeClient } from "@opencode/client/promise"
@@ -40,7 +41,12 @@ export const connect = Effect.fnUntraced(function* (client: OpenCodeClient, stre
Effect.tapCauseIf(Cause.hasDies, (cause) => Effect.logError("ACP request failed", cause)),
Effect.catchDefect((defect) => Effect.fail(ACPError.toRequestError(ACPError.fromUnknown(defect)))),
)
return (ctx: AgentHandlerContext<Params>) => run(handler(ctx))
return (ctx: AgentHandlerContext<Params> & { readonly requestId?: JsonRpcId }) => {
if (ctx.requestId === undefined) return run(handler(ctx))
return run(
handler(ctx).pipe(Effect.provideService(ACPConnection.Responded, acp.connection.responded(ctx.requestId))),
)
}
}
const app = agent({ name: "opencode" })
const request = <Method extends AgentRequestMethod>(
@@ -106,13 +112,13 @@ export const connect = Effect.fnUntraced(function* (client: OpenCodeClient, stre
"session/cancel",
handle((service, ctx) => service.cancel(ctx.params)),
)
const agentConnection = app.connect(stream)
const connection = ACPConnection.make(agentConnection)
const acp = ACPConnection.make(app, stream)
const connection = acp.connection
const sessions = yield* ACPSessions.make({ client, connection, catalog })
const capabilities = yield* Ref.make({ childSessionUpdates: false })
const turn = yield* ACPTurn.make({ client, connection, sessions, catalog, capabilities })
yield* Deferred.succeed(ready, ACPService.make({ client, connection, catalog, sessions, capabilities, turn }))
return agentConnection
return acp.agent
})
const spanName = (method: string) => `cli.acp.${method.replaceAll("/", ".")}`
+49 -11
View File
@@ -1,15 +1,26 @@
import {
methods,
type AgentConnection,
type AgentApp,
type AnyMessage,
type JsonRpcId,
type RequestError,
type RequestPermissionRequest,
type RequestPermissionResponse,
type SessionNotification,
type Stream,
} from "@agentclientprotocol/sdk"
import { Context, type Effect } from "effect"
import { Context, Deferred, Effect } from "effect"
import type { ACPError } from "./error"
import { ACPPromise } from "./promise"
/**
* Completes once the response to the request being handled is written, so messages sent afterwards follow it.
* Interrupts when the request fails. Outside a request it completes immediately.
*/
export const Responded = Context.Reference<Effect.Effect<void>>("@opencode/cli/acp/Connection/Responded", {
defaultValue: () => Effect.void,
})
export interface Interface {
readonly sessionUpdate: (params: SessionNotification) => Effect.Effect<void, ACPError.Error | RequestError>
/** Interruption cancels the client's request. */
@@ -20,20 +31,47 @@ export interface Interface {
method: string,
params: Record<string, unknown>,
) => Effect.Effect<void, ACPError.Error | RequestError>
/** Tracks an incoming request from now on and returns its `Responded`. */
readonly responded: (requestId: JsonRpcId) => Effect.Effect<void>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/cli/acp/Connection") {}
export function make(connection: AgentConnection) {
return Service.of({
sessionUpdate: (params) =>
ACPPromise.promise(() => connection.client.notify(methods.client.session.update, params)),
requestPermission: (params) =>
ACPPromise.promise((signal) =>
connection.client.request(methods.client.session.requestPermission, params, { cancellationSignal: signal }),
),
extNotification: (method, params) => ACPPromise.promise(() => connection.client.notify(method, params)),
export function make(app: AgentApp, stream: Stream) {
// Settled as each response is written to the stream, which serializes every outgoing message.
const responses = new Map<JsonRpcId, Deferred.Deferred<void>>()
const writer = stream.writable.getWriter()
const agent = app.connect({
readable: stream.readable,
writable: new WritableStream<AnyMessage>({
write: async (message) => {
await writer.write(message)
if ("method" in message) return
const responded = responses.get(message.id)
if (!responded) return
responses.delete(message.id)
Deferred.doneUnsafe(responded, "result" in message ? Effect.void : Effect.interrupt)
},
close: () => writer.close(),
abort: (reason) => writer.abort(reason),
}),
})
return {
agent,
connection: Service.of({
sessionUpdate: (params) => ACPPromise.promise(() => agent.client.notify(methods.client.session.update, params)),
requestPermission: (params) =>
ACPPromise.promise((signal) =>
agent.client.request(methods.client.session.requestPermission, params, { cancellationSignal: signal }),
),
extNotification: (method, params) => ACPPromise.promise(() => agent.client.notify(method, params)),
responded: (requestId) => {
const responded = Deferred.makeUnsafe<void>()
responses.set(requestId, responded)
return Deferred.await(responded)
},
}),
}
}
export * as ACPConnection from "./connection"
+9 -4
View File
@@ -191,8 +191,11 @@ export function make(input: {
loadSession: Effect.fnUntraced(function* (params) {
const session = yield* getSession(params.sessionId, params.cwd)
const attached = yield* input.sessions.attach(session, session.location.directory, params.mcpServers)
yield* replay(attached)
return { configOptions: yield* currentOptions(attached) }
return yield* replay(attached).pipe(
Effect.andThen(currentOptions(attached)),
Effect.map((configOptions) => ({ configOptions })),
Effect.onError(() => input.sessions.detach(attached.id)),
)
}),
listSessions: Effect.fnUntraced(function* (params) {
const page = yield* ACPPromise.promise(() =>
@@ -237,8 +240,10 @@ export function make(input: {
forkSession: Effect.fnUntraced(function* (params) {
const forked = yield* ACPPromise.promise(() => input.client.session.fork({ sessionID: params.sessionId }))
const attached = yield* input.sessions.attach(forked, forked.location.directory, params.mcpServers ?? [])
yield* replay(attached)
return { sessionId: attached.id, configOptions: yield* currentOptions(attached) }
return yield* currentOptions(attached).pipe(
Effect.map((configOptions) => ({ sessionId: attached.id, configOptions })),
Effect.onError(() => input.sessions.detach(attached.id)),
)
}),
setSessionConfigOption: Effect.fnUntraced(function* (params) {
const attached = yield* input.sessions.require(params.sessionId)
+25 -24
View File
@@ -4,7 +4,7 @@ import type { OpenCodeClient, OpenCodeEvent, SessionInfo } from "@opencode/clien
import { Context, Deferred, Effect, Exit, Queue, Ref, Scope, Stream } from "effect"
import type { ACPCatalog, Catalog } from "./catalog"
import { availableCommands, configOptions, type Selection } from "./config-option"
import type { ACPConnection } from "./connection"
import { ACPConnection } from "./connection"
import { ACPError } from "./error"
import { ACPPromise } from "./promise"
@@ -16,9 +16,9 @@ export type Attached = {
export interface Interface {
/**
* Attaches a session in its own scope, closing any previous attachment of the same ID. The scope follows the
* cwd's catalog and pushes config option and command updates while it is open. A failed attach leaves the
* session detached.
* Attaches a session in its own scope, closing any previous attachment of the same ID. Once the attaching request
* has responded, the scope follows the cwd's catalog and pushes config option and command updates while it is
* open. A failed attach leaves the session detached.
*/
readonly attach: (
session: SessionInfo,
@@ -141,26 +141,27 @@ export const make = Effect.fnUntraced(function* (input: {
const replaced = sessions.get(session.id)
sessions.set(session.id, entry)
if (replaced) yield* Scope.close(replaced.scope, Exit.void)
yield* registerMcp(entry.attached, mcpServers).pipe(
Effect.andThen(sendCommands(session.id, current)),
Effect.onError(() => remove(session.id, entry)),
)
// `changes` emits the latest catalog first, so a reload since `current` is still pushed. One fold applies
// catalog and selection changes so pushes leave the client on the latest pair.
yield* Stream.merge(
input.catalog.changes(cwd).pipe(Stream.map((catalog) => ({ catalog, patch: {} }))),
Stream.fromQueue(entry.selected).pipe(Stream.map((patch) => ({ catalog: undefined, patch }))),
).pipe(
Stream.runFoldEffect(
() => current,
(previous, step) => {
const next = step.catalog ?? previous
return changed(entry.attached, previous, next, step.patch).pipe(Effect.ignore, Effect.as(next))
},
),
Effect.ignore,
Effect.forkIn(entry.scope),
)
yield* registerMcp(entry.attached, mcpServers).pipe(Effect.onError(() => remove(session.id, entry)))
const responded = yield* ACPConnection.Responded
// Updates wait for the response that hands the client this session. `changes` emits the latest catalog
// first, so a reload since `current` is still pushed. One fold applies catalog and selection changes so
// pushes leave the client on the latest pair.
yield* Effect.gen(function* () {
yield* responded
yield* sendCommands(session.id, current)
yield* Stream.merge(
input.catalog.changes(cwd).pipe(Stream.map((catalog) => ({ catalog, patch: {} }))),
Stream.fromQueue(entry.selected).pipe(Stream.map((patch) => ({ catalog: undefined, patch }))),
).pipe(
Stream.runFoldEffect(
() => current,
(previous, step) => {
const next = step.catalog ?? previous
return changed(entry.attached, previous, next, step.patch).pipe(Effect.ignore, Effect.as(next))
},
),
)
}).pipe(Effect.ignore, Effect.forkIn(entry.scope))
return entry.attached
}),
detach: Effect.fn("cli.acp.sessions.detach")(function* (sessionID) {