Skip to content

Commit 1917f0e

Browse files
authored
fix(acp): fix a batch of ACP issues (#66631)
1 parent d580636 commit 1917f0e

21 files changed

Lines changed: 704 additions & 77 deletions

‎packages/cli/src/acp/catalog.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import type { OpenCodeClient, OpenCodeEvent } from "@opencode/client/effect"
22
import type { Agent } from "@opencode/schema/agent"
33
import type { Command } from "@opencode/schema/command"
44
import type { Model } from "@opencode/schema/model"
5+
import type { Provider } from "@opencode/schema/provider"
6+
import type { Skill } from "@opencode/schema/skill"
57
import { FSUtil } from "@opencode/util/fs-util"
68
import { Cause, Deferred, Effect, Exit, Schedule, Semaphore, Stream, SubscriptionRef } from "effect"
79
import { ACPError } from "./error"
@@ -16,6 +18,9 @@ export type Catalog = {
1618
readonly modes: ReadonlyArray<{ id: Agent.ID; name: string; description?: string }>
1719
readonly defaultModeID: Agent.ID
1820
readonly commands: ReadonlyArray<Command.Info>
21+
/** Skills whose ID no command or built-in command already claims. */
22+
readonly skills: ReadonlyArray<Skill.Info>
23+
readonly providerNames: ReadonlyMap<Provider.ID, string>
1924
}
2025

2126
export function findModel(models: ReadonlyArray<Model.Info>, ref: Model.Ref) {
@@ -36,7 +41,13 @@ type Entry = {
3641
loadedGeneration: number
3742
}
3843

39-
const reloadOn = new Set<OpenCodeEvent["type"]>(["model.updated", "agent.updated", "command.updated"])
44+
const reloadOn = new Set<OpenCodeEvent["type"]>([
45+
"model.updated",
46+
"agent.updated",
47+
"command.updated",
48+
"skill.updated",
49+
"provider.updated",
50+
])
4051

4152
export const make = Effect.fnUntraced(function* (client: OpenCodeClient) {
4253
const scope = yield* Effect.scope
@@ -138,12 +149,14 @@ const load = Effect.fn("cli.acp.catalog.load")(function* (client: OpenCodeClient
138149

139150
const read = Effect.fnUntraced(function* (client: OpenCodeClient, cwd: string) {
140151
const location = { directory: cwd }
141-
const [modelResult, defaultResult, agentResult, commandResult] = yield* Effect.all(
152+
const [modelResult, defaultResult, agentResult, commandResult, skillResult, providerResult] = yield* Effect.all(
142153
[
143154
client.model.list({ location }),
144155
client.model.default({ location }),
145156
client.agent.list({ location }),
146157
client.command.list({ location }),
158+
client.skill.list({ location }),
159+
client.provider.list({ location }),
147160
],
148161
{ concurrency: "unbounded" },
149162
).pipe(Effect.mapError((cause) => new ACPError.CatalogLoadError({ cause })))
@@ -156,6 +169,8 @@ const read = Effect.fnUntraced(function* (client: OpenCodeClient, cwd: string) {
156169
// Core lists its resolved default agent first, the same one a new session runs.
157170
const defaultAgent = agents[0]
158171
if (!defaultAgent) return yield* new ACPError.CatalogNotReadyError({ reason: "agents" })
172+
const commands = commandResult.data.filter((command) => !builtinCommands.has(command.name))
173+
const commandNames = new Set(commands.map((command) => command.name))
159174
return {
160175
models,
161176
defaultModel: {
@@ -165,7 +180,9 @@ const read = Effect.fnUntraced(function* (client: OpenCodeClient, cwd: string) {
165180
},
166181
modes: agents.map((agent) => ({ id: agent.id, name: agent.name, description: agent.description })),
167182
defaultModeID: defaultAgent.id,
168-
commands: commandResult.data.filter((command) => !builtinCommands.has(command.name)),
183+
commands,
184+
skills: skillResult.data.filter((skill) => !builtinCommands.has(skill.id) && !commandNames.has(skill.id)),
185+
providerNames: new Map(providerResult.data.map((provider) => [provider.id, provider.name])),
169186
} satisfies Catalog
170187
})
171188

‎packages/cli/src/acp/child.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { SessionUpdate } from "@agentclientprotocol/sdk"
22

33
export const UpdateMethod = "opencode/session/child_update"
4+
export const MetaKey = "opencode/child-session"
45

56
export type Session = {
67
readonly id: string
@@ -48,7 +49,7 @@ export function project(sessionUpdate: SessionUpdate, child: Session) {
4849

4950
export function meta(child: Session) {
5051
return {
51-
"opencode/child-session": {
52+
[MetaKey]: {
5253
id: child.id,
5354
parentID: child.parentID,
5455
depth: child.depth,

‎packages/cli/src/acp/client.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import { ClientError } from "@opencode/client/effect"
2-
import { InvalidCursorError, InvalidRequestError, SessionNotFoundError } from "@opencode/protocol/errors"
2+
import {
3+
CommandExecutionError,
4+
CommandNotFoundError,
5+
InvalidCursorError,
6+
InvalidRequestError,
7+
SessionNotFoundError,
8+
} from "@opencode/protocol/errors"
39
import { Session } from "@opencode/schema/session"
410
import { Effect, Schema } from "effect"
511
import { HttpClientError } from "effect/http"
@@ -20,6 +26,17 @@ export function classify(error: unknown): Effect.Effect<never, ACPError.Error> {
2026
return Effect.fail(new ACPError.InvalidRequestError({ message: error.message, field: error.field }))
2127
if (error instanceof InvalidCursorError)
2228
return Effect.fail(new ACPError.InvalidRequestError({ message: error.message, field: "cursor" }))
29+
if (error instanceof CommandNotFoundError)
30+
return Effect.fail(new ACPError.InvalidRequestError({ message: error.message, field: "prompt" }))
31+
// The message is the command's own, such as its usage, so the client shows it instead of a generic failure.
32+
if (error instanceof CommandExecutionError)
33+
return Effect.fail(
34+
new ACPError.ServiceFailureError({
35+
safeMessage: error.message,
36+
service: "command",
37+
errorName: "CommandExecutionError",
38+
}),
39+
)
2340
return Effect.die(error)
2441
}
2542

‎packages/cli/src/acp/config-option.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,10 @@ export function configOptions(catalog: Catalog, selection: Selection): SessionCo
3131
currentValue: advertisedModel(model),
3232
options: catalog.models
3333
.toSorted((a, b) => Order.String(a.providerID, b.providerID) || a.name.localeCompare(b.name))
34-
.map((item) => ({ value: advertisedModel(item), name: `${item.providerID}/${item.name}` })),
34+
.map((item) => ({
35+
value: advertisedModel(item),
36+
name: `${catalog.providerNames.get(item.providerID) ?? item.providerID} / ${item.name}`,
37+
})),
3538
},
3639
...(variants.length > 0
3740
? [
@@ -71,6 +74,7 @@ export function availableCommands(catalog: Catalog) {
7174
return [
7275
...catalog.commands.map((command) => ({ name: command.name, description: command.description ?? "" })),
7376
...Array.from(builtinCommands, ([name, command]) => ({ name, description: command.description })),
77+
...catalog.skills.map((skill) => ({ name: skill.id, description: skill.description ?? "" })),
7478
]
7579
}
7680

‎packages/cli/src/acp/content.ts‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ function contentBlockToParts(block: ContentBlock): PromptPart[] {
3434
}
3535
case "resource_link":
3636
return [resourceLinkToPart(block)]
37-
case "resource":
37+
case "resource": {
3838
if ("text" in block.resource) {
3939
const parsed = URL.canParse(block.resource.uri) ? new URL(block.resource.uri) : undefined
4040
const decoded =
@@ -50,17 +50,20 @@ function contentBlockToParts(block: ContentBlock): PromptPart[] {
5050
const filepath = path.sep === "\\" ? decoded.replace(/\\/g, "/") : decoded
5151
return [{ type: "text", text: `[${filepath}${line ? `:${line}` : ""}]\n${block.resource.text}` }]
5252
}
53-
if (!block.resource.mimeType) return []
53+
const filename = filenameFromUri(block.resource.uri) ?? "file"
54+
// ACP makes `mimeType` optional, so infer it from the name rather than dropping the bytes.
55+
const mime = block.resource.mimeType || Bun.file(filename).type.split(";")[0] || "application/octet-stream"
5456
return [
5557
{
5658
type: "file",
5759
url: block.resource.uri.startsWith("data:")
5860
? block.resource.uri
59-
: `data:${block.resource.mimeType};base64,${block.resource.blob}`,
60-
filename: filenameFromUri(block.resource.uri) ?? "file",
61-
mime: block.resource.mimeType,
61+
: `data:${mime};base64,${block.resource.blob}`,
62+
filename,
63+
mime,
6264
},
6365
]
66+
}
6467
default:
6568
return []
6669
}
@@ -136,16 +139,18 @@ export function partsToContentChunks(parts: readonly ReplayPart[]): ContentChunk
136139
}
137140

138141
function resourceLinkToPart(link: ResourceLink): PromptPart {
139-
if (link.uri.startsWith("file://")) {
142+
const parsed = URL.canParse(link.uri) ? new URL(link.uri) : undefined
143+
// `file:/path` and `file:///path` name the same file; the parsed URL spells both as the latter.
144+
if (parsed?.protocol === "file:") {
140145
return {
141146
type: "file",
142-
url: link.uri,
147+
url: parsed.href,
143148
filename: link.name || filenameFromUri(link.uri) || "file",
144149
mime: link.mimeType ?? "text/plain",
145150
}
146151
}
147-
if (link.uri.startsWith("zed://") && URL.canParse(link.uri)) {
148-
const pathname = new URL(link.uri).searchParams.get("path")
152+
if (parsed?.protocol === "zed:") {
153+
const pathname = parsed.searchParams.get("path")
149154
if (pathname)
150155
return {
151156
type: "file",
@@ -165,7 +170,14 @@ function filenameFromUri(uri: string | undefined): string | undefined {
165170
if (!uri || uri.startsWith("data:")) return undefined
166171
if (URL.canParse(uri)) {
167172
const url = new URL(uri)
168-
return path.basename((url.protocol === "zed:" && url.searchParams.get("path")) || url.pathname) || undefined
173+
// Zed's `path` query is already decoded; a URL path is not.
174+
const zedPath = url.protocol === "zed:" ? url.searchParams.get("path") : null
175+
if (zedPath) return path.basename(zedPath) || undefined
176+
return decodeComponent(path.basename(url.pathname)) || undefined
169177
}
170178
return path.basename(uri) || undefined
171179
}
180+
181+
function decodeComponent(value: string) {
182+
return Result.try(() => decodeURIComponent(value)).pipe(Result.getOrElse(() => value))
183+
}

‎packages/cli/src/acp/elicitation.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,9 @@ function cancel(client: OpenCodeClient, form: Form.Info, message?: string) {
5050
export function requestedSchema(form: AskedForm, capabilities: Capabilities): ElicitationSchema | undefined {
5151
if (!capabilities.formElicitation) return undefined
5252
if (Option.isNone(Schema.decodeUnknownOption(ElicitedKind)(form.metadata))) return undefined
53-
if (form.fields.some(credentialLike)) return undefined
54-
const fields = form.fields.filter((field): field is InputField => field.type !== "external")
53+
const elicitedFields = form.fields.map(elicited)
54+
if (elicitedFields.some(collectsSecret)) return undefined
55+
const fields = elicitedFields.filter((field): field is InputField => field.type !== "external")
5556
if (fields.length !== form.fields.length || fields.some((field) => field.when?.length)) return undefined
5657
if (fields.some((field) => field.hidden && field.required && field.default === undefined)) return undefined
5758
const keys = new Set(fields.map((field) => field.key))
@@ -76,7 +77,7 @@ function answer(form: AskedForm, response: CreateElicitationResponse): Form.Answ
7677
const content = Schema.decodeUnknownOption(Form.Answer)(response.content ?? {})
7778
if (Option.isNone(content)) return undefined
7879
return Object.fromEntries(
79-
form.fields.flatMap((field) => {
80+
form.fields.map(elicited).flatMap((field) => {
8081
const value = fieldAnswer(field, content.value)
8182
return value === undefined ? [] : [[field.key, value]]
8283
}),
@@ -108,6 +109,22 @@ export function respond(input: Input, outcome: Form.Answer | "cancel") {
108109
)
109110
}
110111

112+
// A choice can't carry a secret, so a choice worded like one is still asked, without its typed answer.
113+
function elicited(field: Form.Field): Form.Field {
114+
if (!isSelect(field) || !field.custom || !credentialLike(field)) return field
115+
return { ...field, custom: false }
116+
}
117+
118+
function collectsSecret(field: Form.Field) {
119+
if (field.type === "boolean") return false
120+
if (isSelect(field) && !field.custom) return false
121+
return credentialLike(field)
122+
}
123+
124+
function isSelect(field: Form.Field): field is SelectField {
125+
return (field.type === "string" || field.type === "multiselect") && hasOptions(field)
126+
}
127+
111128
function credentialLike(field: Form.Field) {
112129
const labels =
113130
field.type === "string" || field.type === "multiselect" ? (field.options ?? []).map((option) => option.label) : []

‎packages/cli/src/acp/error.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ export class SessionNotFoundError extends Schema.TaggedError<SessionNotFoundErro
77

88
export class SessionDirectoryMismatchError extends Schema.TaggedError<SessionDirectoryMismatchError>()(
99
"ACPSessionDirectoryMismatchError",
10-
{ sessionId: Schema.String, cwd: Schema.String },
10+
{ sessionId: Schema.String, cwd: Schema.String, directory: Schema.String },
1111
) {}
1212

1313
export class InvalidConfigOptionError extends Schema.TaggedError<InvalidConfigOptionError>()(
@@ -48,6 +48,8 @@ export class ServiceFailureError extends Schema.TaggedError<ServiceFailureError>
4848
safeMessage: Schema.String,
4949
service: Schema.optional(Schema.String),
5050
errorName: Schema.optional(Schema.String),
51+
status: Schema.optional(Schema.Number),
52+
retryAfterMs: Schema.optional(Schema.Number),
5153
}) {}
5254

5355
export class ServerUnavailableError extends Schema.TaggedError<ServerUnavailableError>()(
@@ -91,7 +93,7 @@ export function toRequestError(error: Error): RequestError {
9193
return RequestError.invalidParams({ sessionId: error.sessionId }, `session not found: ${error.sessionId}`)
9294
case "ACPSessionDirectoryMismatchError":
9395
return RequestError.invalidParams(
94-
{ sessionId: error.sessionId, cwd: error.cwd },
96+
{ sessionId: error.sessionId, cwd: error.cwd, directory: error.directory },
9597
`session ${error.sessionId} does not belong to cwd: ${error.cwd}`,
9698
)
9799
case "ACPInvalidConfigOptionError":
@@ -121,6 +123,8 @@ export function toRequestError(error: Error): RequestError {
121123
{
122124
...(error.service ? { service: error.service } : {}),
123125
...(error.errorName ? { errorName: error.errorName } : {}),
126+
...(error.status !== undefined ? { status: error.status } : {}),
127+
...(error.retryAfterMs !== undefined ? { retryAfterMs: error.retryAfterMs } : {}),
124128
},
125129
error.safeMessage,
126130
)

‎packages/cli/src/acp/permission.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,8 @@ export const withCompletedDiffs = Effect.fnUntraced(function* (
9797
const path = absolutePath(file.file, cwd)
9898
const newText = file.status === "deleted" ? "" : yield* Effect.tryPromise(() => Bun.file(path).text())
9999
if (file.status === "added") return [diff(path, null, newText)]
100-
const recorded = parsePatch(file.patch)[0]
100+
// A file name with a newline breaks the patch header, and `parsePatch` throws on it.
101+
const recorded = (yield* Effect.try(() => parsePatch(file.patch)))[0]
101102
if (!recorded) return []
102103
const oldText = yield* Effect.try(() => applyPatch(newText, reversePatch(recorded)))
103104
if (oldText !== false) return [diff(path, oldText, newText)]
@@ -109,7 +110,7 @@ export const withCompletedDiffs = Effect.fnUntraced(function* (
109110
return []
110111
const chunks = hunk.chunks.map((chunk) => ({ ...chunk, oldLines: chunk.newLines, newLines: chunk.oldLines }))
111112
const rebuilt = (yield* Effect.try(() => Patch.derive(hunk.path, chunks, newText))).content
112-
return ranges(structuredPatch(path, path, rebuilt, newText)) === ranges(recorded)
113+
return ranges(yield* Effect.try(() => structuredPatch(path, path, rebuilt, newText))) === ranges(recorded)
113114
? [diff(path, rebuilt, newText)]
114115
: []
115116
}).pipe(Effect.orElseSucceed((): Preview[] => [])),

‎packages/cli/src/acp/prompt.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { ContentBlock } from "@agentclientprotocol/sdk"
22
import type { Command } from "@opencode/schema/command"
3+
import type { Skill } from "@opencode/schema/skill"
34
import { SessionMessage } from "@opencode/schema/session-message"
45
import { Effect } from "effect"
56
import { access, constants } from "node:fs/promises"
@@ -16,6 +17,8 @@ export type Prepared = {
1617
readonly synthetic: ReadonlyArray<string>
1718
readonly slash?: { readonly name: string; readonly args: string }
1819
readonly command?: Command.Info
20+
/** A `/skill` prompt sends its text with the skill attached, as an `@skill` mention does elsewhere. */
21+
readonly skills: ReadonlyArray<{ readonly id: Skill.ID }>
1922
}
2023

2124
export const prepare = Effect.fnUntraced(function* (catalog: Catalog, content: readonly ContentBlock[]) {
@@ -39,6 +42,7 @@ export const prepare = Effect.fnUntraced(function* (catalog: Catalog, content: r
3942
synthetic: parts.flatMap((part) => (part.type === "text" && part.synthetic ? [part.text] : [])),
4043
slash,
4144
command: slash ? catalog.commands.find((item) => item.name === slash.name) : undefined,
45+
skills: catalog.skills.flatMap((skill) => (skill.id === slash?.name ? [{ id: skill.id }] : [])),
4246
} satisfies Prepared
4347
})
4448

‎packages/cli/src/acp/service.ts‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { OpenCodeClient } from "@opencode/client/effect"
2+
import { Project } from "@opencode/schema/project"
23
import { AbsolutePath } from "@opencode/schema/schema"
34
import { Session } from "@opencode/schema/session"
45
import { FSUtil } from "@opencode/util/fs-util"
@@ -36,6 +37,7 @@ import type {
3637
import { OPENCODE_VERSION } from "../version"
3738
import { ACPCapabilities, type Capabilities } from "./capabilities"
3839
import type { ACPCatalog } from "./catalog"
40+
import { ACPChild } from "./child"
3941
import { ACPClient } from "./client"
4042
import { configOptions, resolveChange } from "./config-option"
4143
import type { ACPConnection } from "./connection"
@@ -98,9 +100,17 @@ export function make(input: {
98100
const getSession = Effect.fnUntraced(function* (sessionId: string, cwd: string) {
99101
const sessionID = yield* ACPClient.decodeSessionID(sessionId)
100102
const session = yield* input.client.session.get({ sessionID }).pipe(Effect.catch(ACPClient.classify))
101-
if (FSUtil.resolve(cwd) !== FSUtil.resolve(session.location.directory))
102-
return yield* new ACPError.SessionDirectoryMismatchError({ sessionId, cwd })
103-
return session
103+
if (FSUtil.resolve(cwd) === FSUtil.resolve(session.location.directory)) return session
104+
// A session moved into a worktree keeps the client's original cwd, which names the same project.
105+
const location = yield* input.client.location
106+
.get({ location: { directory: AbsolutePath.make(cwd) } })
107+
.pipe(Effect.catch(ACPClient.classify))
108+
if (location.project.id !== Project.ID.global && location.project.id === session.projectID) return session
109+
return yield* new ACPError.SessionDirectoryMismatchError({
110+
sessionId,
111+
cwd,
112+
directory: session.location.directory,
113+
})
104114
})
105115

106116
// Clients often open a session and close it without prompting; closing removes those instead of keeping an empty session.
@@ -201,6 +211,17 @@ export function make(input: {
201211
time: { created: DateTime.toEpochMillis(session.time.created) },
202212
}),
203213
updatedAt: DateTime.formatIso(session.time.updated),
214+
...(session.parentID
215+
? {
216+
_meta: {
217+
[ACPChild.MetaKey]: {
218+
id: session.id,
219+
parentID: session.parentID,
220+
...(session.title ? { title: session.title } : {}),
221+
},
222+
},
223+
}
224+
: {}),
204225
}
205226
}),
206227
...(page.cursor.next ? { nextCursor: page.cursor.next } : {}),

0 commit comments

Comments
 (0)