mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 21:15:57 +03:00
refactor(acp): split module seams and drop dead code (#52803)
This commit is contained in:
committed by
GitHub
Unverified
parent
9f8551ab6b
commit
66d15a7352
@@ -11,6 +11,7 @@ import {
|
||||
} from "@agentclientprotocol/sdk"
|
||||
import type { OpenCodeClient } from "@opencode/client/effect"
|
||||
import { Cause, Deferred, Effect, Ref, type Scope } from "effect"
|
||||
import { ACPCapabilities } from "./capabilities"
|
||||
import { ACPCatalog } from "./catalog"
|
||||
import { ACPClient } from "./client"
|
||||
import { ACPConnection } from "./connection"
|
||||
@@ -27,7 +28,7 @@ export const connect = Effect.fnUntraced(function* (client: OpenCodeClient, stre
|
||||
const ready = yield* Deferred.make<ACPService.Interface>()
|
||||
const handle =
|
||||
<Params, A>(
|
||||
call: (service: ACPService.Interface, ctx: AgentHandlerContext<Params>) => Effect.Effect<A, ACPService.Failure>,
|
||||
call: (service: ACPService.Interface, ctx: AgentHandlerContext<Params>) => Effect.Effect<A, ACPError.Failure>,
|
||||
) =>
|
||||
(name: string) => {
|
||||
const handler = Effect.fn(name)(
|
||||
@@ -114,7 +115,7 @@ export const connect = Effect.fnUntraced(function* (client: OpenCodeClient, stre
|
||||
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, formElicitation: false, compaction: false })
|
||||
const capabilities = yield* Ref.make(ACPCapabilities.parse(undefined))
|
||||
const turn = yield* ACPTurn.make({ client, connection, sessions, catalog, capabilities })
|
||||
yield* Deferred.succeed(ready, ACPService.make({ client, connection, catalog, sessions, capabilities, turn }))
|
||||
return acp.agent
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { ClientCapabilities } from "@agentclientprotocol/sdk"
|
||||
|
||||
export const ChildSessionUpdates = "opencode/child-session-updates"
|
||||
|
||||
export type Capabilities = ReturnType<typeof parse>
|
||||
|
||||
export function parse(client: ClientCapabilities | undefined) {
|
||||
const elicitation = client?.elicitation
|
||||
const compaction = client?.session?.compaction
|
||||
return {
|
||||
childSessionUpdates: client?._meta?.[ChildSessionUpdates] === true,
|
||||
formElicitation: elicitation?.form !== undefined && elicitation.form !== null,
|
||||
compaction: compaction !== undefined && compaction !== null,
|
||||
}
|
||||
}
|
||||
|
||||
export * as ACPCapabilities from "./capabilities"
|
||||
@@ -3,7 +3,7 @@ import type { Agent } from "@opencode/schema/agent"
|
||||
import type { Command } from "@opencode/schema/command"
|
||||
import type { Model } from "@opencode/schema/model"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
import { Cause, Context, Deferred, Effect, Exit, Schedule, Schema, Semaphore, Stream, SubscriptionRef } from "effect"
|
||||
import { Cause, Deferred, Effect, Exit, Schedule, Schema, Semaphore, Stream, SubscriptionRef } from "effect"
|
||||
import type { ConfigOptionProvider } from "./config-option"
|
||||
|
||||
export const builtinCommands = new Map([
|
||||
@@ -19,7 +19,7 @@ export type Catalog = {
|
||||
readonly commands: ReadonlyArray<Command.Info>
|
||||
}
|
||||
|
||||
export class NotReadyError extends Schema.TaggedError<NotReadyError>()("ACPCatalogNotReadyError", {
|
||||
class NotReadyError extends Schema.TaggedError<NotReadyError>()("ACPCatalogNotReadyError", {
|
||||
reason: Schema.Literals(["models", "agents"]),
|
||||
}) {
|
||||
override get message() {
|
||||
@@ -27,7 +27,7 @@ export class NotReadyError extends Schema.TaggedError<NotReadyError>()("ACPCatal
|
||||
}
|
||||
}
|
||||
|
||||
export class LoadError extends Schema.TaggedError<LoadError>()("ACPCatalogLoadError", {
|
||||
class LoadError extends Schema.TaggedError<LoadError>()("ACPCatalogLoadError", {
|
||||
cause: Schema.Defect(),
|
||||
}) {}
|
||||
|
||||
@@ -39,14 +39,12 @@ export interface Interface {
|
||||
readonly changes: (cwd: string) => Stream.Stream<Catalog, Error>
|
||||
}
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/cli/acp/Catalog") {}
|
||||
|
||||
type Entry = {
|
||||
readonly cwd: string
|
||||
readonly catalog: SubscriptionRef.SubscriptionRef<Catalog>
|
||||
readonly lock: Semaphore.Semaphore
|
||||
requested: number
|
||||
loaded: number
|
||||
requestedGeneration: number
|
||||
loadedGeneration: number
|
||||
}
|
||||
|
||||
const reloadOn = new Set<OpenCodeEvent["type"]>(["model.updated", "agent.updated", "command.updated"])
|
||||
@@ -59,17 +57,17 @@ export const make = Effect.fnUntraced(function* (client: OpenCodeClient) {
|
||||
// Requests queued behind a running load share the next one.
|
||||
const reload = (entry: Entry) =>
|
||||
Effect.suspend(() => {
|
||||
const target = ++entry.requested
|
||||
const target = ++entry.requestedGeneration
|
||||
return entry.lock.withPermit(
|
||||
Effect.suspend(() => {
|
||||
if (entry.loaded >= target) return Effect.void
|
||||
const generation = entry.requested
|
||||
if (entry.loadedGeneration >= target) return Effect.void
|
||||
const generation = entry.requestedGeneration
|
||||
return load(client, entry.cwd).pipe(
|
||||
Effect.flatMap((next) => SubscriptionRef.set(entry.catalog, next)),
|
||||
Effect.ignore,
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
entry.loaded = generation
|
||||
entry.loadedGeneration = generation
|
||||
}),
|
||||
),
|
||||
)
|
||||
@@ -103,8 +101,8 @@ export const make = Effect.fnUntraced(function* (client: OpenCodeClient) {
|
||||
cwd,
|
||||
catalog: yield* SubscriptionRef.make<Catalog>(yield* load(client, cwd)),
|
||||
lock: Semaphore.makeUnsafe(1),
|
||||
requested: 0,
|
||||
loaded: 0,
|
||||
requestedGeneration: 0,
|
||||
loadedGeneration: 0,
|
||||
} satisfies Entry
|
||||
})
|
||||
|
||||
@@ -125,8 +123,8 @@ export const make = Effect.fnUntraced(function* (client: OpenCodeClient) {
|
||||
)
|
||||
})
|
||||
|
||||
return Service.of({
|
||||
get: Effect.fn("cli.acp.catalog.get")(function* (cwd) {
|
||||
return {
|
||||
get: Effect.fnUntraced(function* (cwd) {
|
||||
const loaded = yield* entry(cwd)
|
||||
return yield* SubscriptionRef.get(loaded.catalog)
|
||||
}),
|
||||
@@ -134,7 +132,7 @@ export const make = Effect.fnUntraced(function* (client: OpenCodeClient) {
|
||||
yield* reload(yield* entry(cwd))
|
||||
}),
|
||||
changes: (cwd) => Stream.unwrap(entry(cwd).pipe(Effect.map((loaded) => SubscriptionRef.changes(loaded.catalog)))),
|
||||
})
|
||||
} satisfies Interface
|
||||
})
|
||||
|
||||
const load = (client: OpenCodeClient, cwd: string) =>
|
||||
@@ -183,7 +181,7 @@ const read = Effect.fnUntraced(function* (client: OpenCodeClient, cwd: string) {
|
||||
} satisfies Catalog
|
||||
})
|
||||
|
||||
function providers(models: ReadonlyArray<Model.Info>): ConfigOptionProvider[] {
|
||||
function providers(models: ReadonlyArray<Model.Info>) {
|
||||
return Array.from(new Set(models.map((model) => model.providerID)))
|
||||
.toSorted()
|
||||
.map((providerID) => ({
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { SessionUpdate } from "@agentclientprotocol/sdk"
|
||||
|
||||
export const UpdateMethod = "opencode/session/child_update"
|
||||
|
||||
export type Session = {
|
||||
readonly id: string
|
||||
readonly parentID: string
|
||||
readonly depth: number
|
||||
readonly title?: string
|
||||
}
|
||||
|
||||
export type Event =
|
||||
| { readonly type: "update"; readonly update: SessionUpdate }
|
||||
| {
|
||||
readonly type: "status"
|
||||
readonly status: "created" | "running" | "completed" | "failed" | "interrupted"
|
||||
readonly error?: { readonly type: string; readonly message: string }
|
||||
}
|
||||
|
||||
export type Update = {
|
||||
readonly rootSessionId: string
|
||||
readonly childSessionId: string
|
||||
readonly parentSessionId: string
|
||||
readonly depth: number
|
||||
readonly title?: string
|
||||
} & Event
|
||||
|
||||
export function update(rootSessionID: string, child: Session, event: Event): Update {
|
||||
return {
|
||||
rootSessionId: rootSessionID,
|
||||
childSessionId: child.id,
|
||||
parentSessionId: child.parentID,
|
||||
depth: child.depth,
|
||||
...(child.title ? { title: child.title } : {}),
|
||||
...event,
|
||||
}
|
||||
}
|
||||
|
||||
export function project(sessionUpdate: SessionUpdate, child: Session) {
|
||||
const projected = { ...sessionUpdate }
|
||||
projected._meta = { ...projected._meta, ...meta(child) }
|
||||
if (projected.sessionUpdate === "tool_call" || projected.sessionUpdate === "tool_call_update") {
|
||||
projected.toolCallId = toolCallID(child, projected.toolCallId)
|
||||
if (projected.title) projected.title = prefixTitle(child, projected.title)
|
||||
}
|
||||
return projected
|
||||
}
|
||||
|
||||
export function meta(child: Session) {
|
||||
return {
|
||||
"opencode/child-session": {
|
||||
id: child.id,
|
||||
parentID: child.parentID,
|
||||
depth: child.depth,
|
||||
...(child.title ? { title: child.title } : {}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function toolCallID(child: Session | undefined, id: string) {
|
||||
return child ? `${child.id}:${id}` : id
|
||||
}
|
||||
|
||||
export function prefixTitle(child: Session | undefined, value: string) {
|
||||
return child?.title ? `${child.title}: ${value}` : value
|
||||
}
|
||||
|
||||
export * as ACPChild from "./child"
|
||||
@@ -9,7 +9,9 @@ export function classify(error: unknown): Effect.Effect<never, ACPError.Error> {
|
||||
if (
|
||||
error instanceof ClientError &&
|
||||
HttpClientError.isHttpClientError(error.cause) &&
|
||||
isConnectionFailure(error.cause)
|
||||
// The client reports a failed body read as a `DecodeError` with a cause; its other `DecodeError`s have none.
|
||||
(error.cause.reason._tag === "TransportError" ||
|
||||
(error.cause.reason._tag === "DecodeError" && error.cause.reason.cause !== undefined))
|
||||
)
|
||||
return Effect.fail(new ACPError.ServerUnavailableError())
|
||||
if (error instanceof SessionNotFoundError)
|
||||
@@ -21,13 +23,6 @@ export function classify(error: unknown): Effect.Effect<never, ACPError.Error> {
|
||||
return Effect.die(error)
|
||||
}
|
||||
|
||||
// The client reports a failed body read as a `DecodeError` with a cause; its other `DecodeError`s have none.
|
||||
function isConnectionFailure(error: HttpClientError.HttpClientError) {
|
||||
return (
|
||||
error.reason._tag === "TransportError" || (error.reason._tag === "DecodeError" && error.reason.cause !== undefined)
|
||||
)
|
||||
}
|
||||
|
||||
export function decodeSessionID(value: string) {
|
||||
return Schema.decodeUnknownEffect(Session.ID)(value).pipe(
|
||||
Effect.mapError(() => new ACPError.InvalidRequestError({ message: "Invalid session ID", field: "sessionID" })),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { SessionMessage } from "@opencode/schema/session-message"
|
||||
|
||||
const MarkerMeta = "opencode/compaction"
|
||||
|
||||
export type Started = { readonly status: "started"; readonly messageId: string; readonly reason: "auto" | "manual" }
|
||||
type Started = { readonly status: "started"; readonly messageId: string; readonly reason: "auto" | "manual" }
|
||||
|
||||
type Compaction =
|
||||
| Started
|
||||
@@ -43,11 +43,11 @@ export function usesStandardUpdates(
|
||||
return ctx.compaction && (!child || ctx.childUpdates)
|
||||
}
|
||||
|
||||
export function apply(event: LifecycleEvent, tracked: Tracked, standard: boolean) {
|
||||
export function apply(event: LifecycleEvent, tracked: Tracked, standardUpdates: boolean) {
|
||||
const sessionID = event.data.sessionID
|
||||
if (event.type === "session.compaction.started") {
|
||||
const started = open(event)
|
||||
return { tracked: new Map(tracked).set(sessionID, started), updates: [update(started, standard)] }
|
||||
return { tracked: new Map(tracked).set(sessionID, started), updates: [update(started, standardUpdates)] }
|
||||
}
|
||||
const current = tracked.get(sessionID)
|
||||
const remaining = new Map(tracked)
|
||||
@@ -60,35 +60,41 @@ export function apply(event: LifecycleEvent, tracked: Tracked, standard: boolean
|
||||
reason: event.data.reason,
|
||||
summary: event.data.text,
|
||||
}
|
||||
return { tracked: remaining, updates: [update(completed, standard)] }
|
||||
return { tracked: remaining, updates: [update(completed, standardUpdates)] }
|
||||
}
|
||||
// Auto compaction can fail without a started event; open it first for standard clients.
|
||||
const started = current ?? open(event)
|
||||
const failed: Compaction = { ...started, status: "failed", reason: event.data.reason, error: event.data.error }
|
||||
return {
|
||||
tracked: remaining,
|
||||
updates: [...(current || !standard ? [] : [update(started, standard)]), update(failed, standard)],
|
||||
updates: [
|
||||
...(current || !standardUpdates ? [] : [update(started, standardUpdates)]),
|
||||
update(failed, standardUpdates),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
export function chunk(started: Started | undefined, text: string, standard: boolean): SessionUpdate | undefined {
|
||||
if (!started || !standard) return undefined
|
||||
export function chunk(started: Started | undefined, text: string, standardUpdates: boolean): SessionUpdate | undefined {
|
||||
if (!started || !standardUpdates) return undefined
|
||||
return { sessionUpdate: "compaction_summary_chunk", compactionId: started.messageId, content: { type: "text", text } }
|
||||
}
|
||||
|
||||
export function abandon(started: Started, standard: boolean) {
|
||||
return update({ ...started, status: "failed", error: { type: "aborted", message: "Compaction cancelled" } }, standard)
|
||||
export function abandon(started: Started, standardUpdates: boolean) {
|
||||
return update(
|
||||
{ ...started, status: "failed", error: { type: "aborted", message: "Compaction cancelled" } },
|
||||
standardUpdates,
|
||||
)
|
||||
}
|
||||
|
||||
// Nothing on this connection would settle a replayed running compaction.
|
||||
export function replay(message: Extract<SessionMessage.Info, { type: "compaction" }>, standard: boolean) {
|
||||
export function replay(message: Extract<SessionMessage.Info, { type: "compaction" }>, standardUpdates: boolean) {
|
||||
if (message.status === "running") return undefined
|
||||
const base = { messageId: message.id, reason: message.reason }
|
||||
return update(
|
||||
message.status === "failed"
|
||||
? { ...base, status: "failed", error: message.error }
|
||||
: { ...base, status: "completed", summary: message.summary },
|
||||
standard,
|
||||
standardUpdates,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -101,8 +107,8 @@ function open(event: OpeningEvent): Started {
|
||||
}
|
||||
}
|
||||
|
||||
function update(compaction: Compaction, standard: boolean): SessionUpdate {
|
||||
if (!standard) {
|
||||
function update(compaction: Compaction, standardUpdates: boolean): SessionUpdate {
|
||||
if (!standardUpdates) {
|
||||
const marker = {
|
||||
status: compaction.status,
|
||||
messageId: compaction.messageId,
|
||||
@@ -125,12 +131,12 @@ function update(compaction: Compaction, standard: boolean): SessionUpdate {
|
||||
compactionId,
|
||||
status: "failed",
|
||||
summary: null,
|
||||
error: errorMessage(compaction.error),
|
||||
error: displayError(compaction.error),
|
||||
}
|
||||
}
|
||||
|
||||
// Core reports a defect as `compaction.failed` with a multi-line pretty-printed cause.
|
||||
function errorMessage(error: SessionError.Error) {
|
||||
function displayError(error: SessionError.Error) {
|
||||
if (!error.message || (error.type === "compaction.failed" && error.message.includes("\n"))) return "Compaction failed"
|
||||
return error.message
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { builtinCommands, type Catalog } from "./catalog"
|
||||
|
||||
export const DEFAULT_VARIANT_VALUE = "default"
|
||||
|
||||
export type ConfigOptionModel = {
|
||||
type ConfigOptionModel = {
|
||||
id: string
|
||||
name: string
|
||||
variants?: ReadonlyArray<string>
|
||||
@@ -17,7 +17,7 @@ export type ConfigOptionProvider = {
|
||||
models: ReadonlyArray<ConfigOptionModel>
|
||||
}
|
||||
|
||||
export type ConfigOptionMode = {
|
||||
type ConfigOptionMode = {
|
||||
id: string
|
||||
name: string
|
||||
description?: string
|
||||
@@ -163,5 +163,3 @@ function selectVariant(variant: string | undefined, variants: readonly string[])
|
||||
if (variants.includes(DEFAULT_VARIANT_VALUE)) return DEFAULT_VARIANT_VALUE
|
||||
return variants[0] ?? DEFAULT_VARIANT_VALUE
|
||||
}
|
||||
|
||||
export * as ACPConfigOption from "./config-option"
|
||||
|
||||
@@ -29,8 +29,6 @@ export interface Interface {
|
||||
readonly responded: (requestId: JsonRpcId) => Effect.Effect<void>
|
||||
}
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/cli/acp/Connection") {}
|
||||
|
||||
export function make(app: AgentApp, stream: Stream) {
|
||||
const responses = new Map<JsonRpcId, Deferred.Deferred<void>>()
|
||||
const writer = stream.writable.getWriter()
|
||||
@@ -51,7 +49,7 @@ export function make(app: AgentApp, stream: Stream) {
|
||||
})
|
||||
return {
|
||||
agent,
|
||||
connection: Service.of({
|
||||
connection: {
|
||||
sessionUpdate: (params) => promise(() => agent.client.notify(methods.client.session.update, params)),
|
||||
requestPermission: (params) =>
|
||||
promise((signal) =>
|
||||
@@ -67,7 +65,7 @@ export function make(app: AgentApp, stream: Stream) {
|
||||
responses.set(requestId, responded)
|
||||
return Deferred.await(responded)
|
||||
},
|
||||
}),
|
||||
} satisfies Interface,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import type { ContentBlock, ContentChunk, ResourceLink } from "@agentclientprotocol/sdk"
|
||||
import path from "node:path"
|
||||
import { fileURLToPath, pathToFileURL } from "node:url"
|
||||
import { Result } from "effect"
|
||||
|
||||
export type PromptPart =
|
||||
| { readonly type: "text"; readonly text: string; readonly synthetic?: boolean; readonly ignored?: boolean }
|
||||
| { readonly type: "file"; readonly url: string; readonly filename?: string; readonly mime: string }
|
||||
|
||||
export type ReplayPart = PromptPart | { readonly type: "reasoning"; readonly text: string }
|
||||
type ReplayPart = PromptPart | { readonly type: "reasoning"; readonly text: string }
|
||||
|
||||
export function promptContentToParts(content: readonly ContentBlock[]): PromptPart[] {
|
||||
return content.flatMap(contentBlockToParts)
|
||||
}
|
||||
|
||||
export function contentBlockToParts(block: ContentBlock): PromptPart[] {
|
||||
function contentBlockToParts(block: ContentBlock): PromptPart[] {
|
||||
switch (block.type) {
|
||||
case "text": {
|
||||
const audience = block.annotations?.audience
|
||||
@@ -35,22 +36,19 @@ export function contentBlockToParts(block: ContentBlock): PromptPart[] {
|
||||
return [resourceLinkToPart(block)]
|
||||
case "resource":
|
||||
if ("text" in block.resource) {
|
||||
try {
|
||||
const parsed = new URL(block.resource.uri)
|
||||
if (parsed.protocol === "file:") {
|
||||
const line = parsed.hash.match(/^#L(\d+)/)?.[1]
|
||||
const decoded = (() => {
|
||||
try {
|
||||
return fileURLToPath(parsed)
|
||||
} catch {
|
||||
return decodeURIComponent(parsed.pathname)
|
||||
}
|
||||
})()
|
||||
const filepath = path.sep === "\\" ? decoded.replace(/\\/g, "/") : decoded
|
||||
return [{ type: "text", text: `[${filepath}${line ? `:${line}` : ""}]\n${block.resource.text}` }]
|
||||
}
|
||||
} catch {}
|
||||
return [{ type: "text", text: `[${block.resource.uri}]\n${block.resource.text}` }]
|
||||
const parsed = URL.canParse(block.resource.uri) ? new URL(block.resource.uri) : undefined
|
||||
const decoded =
|
||||
parsed?.protocol === "file:"
|
||||
? Result.try(() => fileURLToPath(parsed)).pipe(
|
||||
Result.orElse(() => Result.try(() => decodeURIComponent(parsed.pathname))),
|
||||
Result.getOrUndefined,
|
||||
)
|
||||
: undefined
|
||||
if (!parsed || decoded === undefined)
|
||||
return [{ type: "text", text: `[${block.resource.uri}]\n${block.resource.text}` }]
|
||||
const line = parsed.hash.match(/^#L(\d+)/)?.[1]
|
||||
const filepath = path.sep === "\\" ? decoded.replace(/\\/g, "/") : decoded
|
||||
return [{ type: "text", text: `[${filepath}${line ? `:${line}` : ""}]\n${block.resource.text}` }]
|
||||
}
|
||||
if (!block.resource.mimeType) return []
|
||||
return [
|
||||
@@ -171,5 +169,3 @@ function filenameFromUri(uri: string | undefined): string | undefined {
|
||||
}
|
||||
return path.basename(uri) || undefined
|
||||
}
|
||||
|
||||
export * as ACPContent from "./content"
|
||||
|
||||
@@ -6,10 +6,11 @@ import type {
|
||||
} from "@agentclientprotocol/sdk"
|
||||
import type { OpenCodeClient } from "@opencode/client/effect"
|
||||
import { Form } from "@opencode/schema/form"
|
||||
import { Session } from "@opencode/schema/session"
|
||||
import { Cause, Effect, Option, Schema } from "effect"
|
||||
import type { Capabilities } from "./capabilities"
|
||||
import { ACPChild } from "./child"
|
||||
import { ACPClient } from "./client"
|
||||
import type { ACPConnection } from "./connection"
|
||||
import type { ACPService } from "./service"
|
||||
|
||||
export type AskedForm = Omit<Form.Info, "id"> & { readonly id: string }
|
||||
type InputField = Exclude<Form.Field, Form.ExternalField>
|
||||
@@ -27,7 +28,7 @@ type Input = {
|
||||
readonly form: Form.Info
|
||||
readonly requestedSchema: ElicitationSchema
|
||||
readonly clientSessionID: string
|
||||
readonly child?: { readonly id: string; readonly title?: string }
|
||||
readonly child?: ACPChild.Session
|
||||
readonly toolCallSent: boolean
|
||||
readonly settled: Effect.Effect<void>
|
||||
}
|
||||
@@ -58,7 +59,7 @@ function cancel(client: OpenCodeClient, form: Form.Info, message?: string) {
|
||||
return client.session.form.cancel({ sessionID: form.sessionID, formID: form.id, message }).pipe(
|
||||
Effect.catchTag(["FormAlreadySettledError", "FormNotFoundError"], () => Effect.void),
|
||||
Effect.catch(() =>
|
||||
Schema.decodeUnknownEffect(Session.ID)(form.sessionID).pipe(
|
||||
ACPClient.decodeSessionID(form.sessionID).pipe(
|
||||
Effect.flatMap((sessionID) => client.session.interrupt({ sessionID })),
|
||||
Effect.ignore,
|
||||
),
|
||||
@@ -66,7 +67,7 @@ function cancel(client: OpenCodeClient, form: Form.Info, message?: string) {
|
||||
)
|
||||
}
|
||||
|
||||
export function requestedSchema(form: AskedForm, capabilities: ACPService.Capabilities): ElicitationSchema | undefined {
|
||||
export function requestedSchema(form: AskedForm, capabilities: Capabilities): ElicitationSchema | undefined {
|
||||
if (!capabilities.formElicitation) return undefined
|
||||
if (Option.isNone(Schema.decodeUnknownOption(ElicitedKind)(form.metadata))) return undefined
|
||||
if (form.fields.some(credentialLike)) return undefined
|
||||
@@ -90,7 +91,7 @@ export function cancelUnshown(client: OpenCodeClient, form: Form.Info) {
|
||||
)
|
||||
}
|
||||
|
||||
export function answer(form: AskedForm, response: CreateElicitationResponse): Form.Answer | undefined {
|
||||
function answer(form: AskedForm, response: CreateElicitationResponse): Form.Answer | undefined {
|
||||
if (response.action !== "accept") return undefined
|
||||
const content = Schema.decodeUnknownOption(Form.Answer)(response.content ?? {})
|
||||
if (Option.isNone(content)) return undefined
|
||||
@@ -108,8 +109,8 @@ const ask = Effect.fnUntraced(function* (input: Input) {
|
||||
const response = yield* input.connection.createElicitation({
|
||||
mode: "form",
|
||||
sessionId: input.clientSessionID,
|
||||
...(toolCallID ? { toolCallId: input.child ? `${input.child.id}:${toolCallID}` : toolCallID } : {}),
|
||||
message: input.child?.title ? `${input.child.title}: ${input.form.title}` : input.form.title,
|
||||
...(toolCallID ? { toolCallId: ACPChild.toolCallID(input.child, toolCallID) } : {}),
|
||||
message: ACPChild.prefixTitle(input.child, input.form.title),
|
||||
requestedSchema: input.requestedSchema,
|
||||
})
|
||||
return answer(input.form, response) ?? "cancel"
|
||||
@@ -152,7 +153,8 @@ function properties(field: InputField): Array<[string, ElicitationPropertySchema
|
||||
const base = { title: field.title, description: field.description }
|
||||
switch (field.type) {
|
||||
case "string": {
|
||||
if (!hasOptions(field)) return [[field.key, { type: "string", ...base, ...text(field), default: field.default }]]
|
||||
if (!hasOptions(field))
|
||||
return [[field.key, { type: "string", ...base, ...stringConstraints(field), default: field.default }]]
|
||||
const select: ElicitationPropertySchema = {
|
||||
type: "string",
|
||||
...base,
|
||||
@@ -192,13 +194,13 @@ function other(field: SelectField, description: string): [string, ElicitationPro
|
||||
type: "string",
|
||||
title: `${field.title ?? field.key} (other)`,
|
||||
description,
|
||||
...(field.type === "string" ? text(field) : {}),
|
||||
...(field.type === "string" ? stringConstraints(field) : {}),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
// Core rejects an empty string for a required field.
|
||||
function text(field: Form.StringField) {
|
||||
function stringConstraints(field: Form.StringField) {
|
||||
return {
|
||||
format: field.format,
|
||||
minLength: field.required ? Math.max(field.minLength ?? 0, 1) : field.minLength,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { RequestError } from "@agentclientprotocol/sdk"
|
||||
import { Schema } from "effect"
|
||||
import type { ACPCatalog } from "./catalog"
|
||||
|
||||
export class SessionNotFoundError extends Schema.TaggedError<SessionNotFoundError>()("ACPSessionNotFoundError", {
|
||||
sessionId: Schema.String,
|
||||
@@ -55,22 +56,21 @@ export class ServerUnavailableError extends Schema.TaggedError<ServerUnavailable
|
||||
{},
|
||||
) {}
|
||||
|
||||
const Errors = Schema.Union([
|
||||
SessionNotFoundError,
|
||||
SessionDirectoryMismatchError,
|
||||
InvalidConfigOptionError,
|
||||
InvalidModelError,
|
||||
InvalidEffortError,
|
||||
InvalidModeError,
|
||||
InvalidAdditionalDirectoryError,
|
||||
AuthRequiredError,
|
||||
UnknownAuthMethodError,
|
||||
InvalidRequestError,
|
||||
ServiceFailureError,
|
||||
ServerUnavailableError,
|
||||
])
|
||||
export type Error =
|
||||
| SessionNotFoundError
|
||||
| SessionDirectoryMismatchError
|
||||
| InvalidConfigOptionError
|
||||
| InvalidModelError
|
||||
| InvalidEffortError
|
||||
| InvalidModeError
|
||||
| InvalidAdditionalDirectoryError
|
||||
| AuthRequiredError
|
||||
| UnknownAuthMethodError
|
||||
| InvalidRequestError
|
||||
| ServiceFailureError
|
||||
| ServerUnavailableError
|
||||
|
||||
export type Error = typeof Errors.Type
|
||||
export type Failure = Error | RequestError | ACPCatalog.Error
|
||||
|
||||
export function toRequestError(error: Error): RequestError {
|
||||
switch (error._tag) {
|
||||
@@ -118,9 +118,9 @@ export function toRequestError(error: Error): RequestError {
|
||||
return exhaustive
|
||||
}
|
||||
|
||||
export function fromUnknown(error: unknown, service?: string) {
|
||||
export function fromUnknown(error: unknown) {
|
||||
const errorName = error instanceof Error ? error.name : undefined
|
||||
return new ServiceFailureError({ safeMessage: "Internal service failure", service, errorName })
|
||||
return new ServiceFailureError({ safeMessage: "Internal service failure", errorName })
|
||||
}
|
||||
|
||||
export * as ACPError from "./error"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PermissionOption, ToolCallLocation } from "@agentclientprotocol/sdk"
|
||||
import type { PermissionOption } from "@agentclientprotocol/sdk"
|
||||
import type { OpenCodeClient, OpenCodeEvent } from "@opencode/client/effect"
|
||||
import { FileDiff } from "@opencode/schema/file-diff"
|
||||
import type { Permission } from "@opencode/schema/permission"
|
||||
@@ -6,9 +6,9 @@ import type { Session } from "@opencode/schema/session"
|
||||
import { Patch } from "@opencode/util/patch"
|
||||
import { applyPatch } from "diff"
|
||||
import { Cause, Effect, Option, Schema } from "effect"
|
||||
import { ACPChild } from "./child"
|
||||
import { ACPClient } from "./client"
|
||||
import type { ACPConnection } from "./connection"
|
||||
import { ACPTranslate } from "./translate"
|
||||
import { absolutePath, filePath, patchHunks, pendingToolCall, stringValue, toLocations, type ToolInput } from "./tool"
|
||||
|
||||
type PermissionEvent = Extract<OpenCodeEvent, { type: "permission.asked" }>
|
||||
@@ -23,7 +23,7 @@ type Input = {
|
||||
readonly clientSessionID: string
|
||||
readonly cwd: string
|
||||
readonly tool?: Tool
|
||||
readonly child?: ACPTranslate.ChildSession
|
||||
readonly child?: ACPChild.Session
|
||||
readonly settled: Effect.Effect<void>
|
||||
}
|
||||
|
||||
@@ -58,14 +58,11 @@ const ask = Effect.fnUntraced(function* (input: Input) {
|
||||
const previews = yield* permissionPreviews(toolName, toolInput, input.event.data.metadata, input.cwd).pipe(
|
||||
Effect.orElseSucceed((): Preview[] => []),
|
||||
)
|
||||
const toolCallID = input.tool?.id ?? input.event.data.id
|
||||
const title = permissionTitle(toolName, toolInput, previews)
|
||||
const toolCall = pendingToolCall({
|
||||
toolCallId: input.child ? `${input.child.id}:${toolCallID}` : toolCallID,
|
||||
toolCallId: ACPChild.toolCallID(input.child, input.tool?.id ?? input.event.data.id),
|
||||
toolName,
|
||||
state: {
|
||||
input: toolInput,
|
||||
title: prefixedTitle(input.child?.title, permissionTitle(toolName, toolInput, previews)),
|
||||
},
|
||||
state: { input: toolInput, title: title ? ACPChild.prefixTitle(input.child, title) : input.child?.title },
|
||||
cwd: input.cwd,
|
||||
})
|
||||
const result = yield* input.connection.requestPermission({
|
||||
@@ -75,7 +72,7 @@ const ask = Effect.fnUntraced(function* (input: Input) {
|
||||
rawInput: input.tool ? toolCall.rawInput : undefined,
|
||||
locations: permissionLocations(toolName, toolInput, input.event.data, input.cwd),
|
||||
...(previews.length > 0 ? { content: previews } : {}),
|
||||
...(input.child ? { _meta: ACPTranslate.childSessionMeta(input.child) } : {}),
|
||||
...(input.child ? { _meta: ACPChild.meta(input.child) } : {}),
|
||||
},
|
||||
options,
|
||||
})
|
||||
@@ -91,12 +88,6 @@ function respond(input: Input, decision: Permission.Reply | "settled") {
|
||||
)
|
||||
}
|
||||
|
||||
function prefixedTitle(prefix: string | undefined, title: string | undefined) {
|
||||
if (!prefix) return title
|
||||
if (!title) return prefix
|
||||
return `${prefix}: ${title}`
|
||||
}
|
||||
|
||||
// Core trims the patch tool's diffs for display, which breaks `applyPatch`, so its previews come from its own hunks.
|
||||
const permissionPreviews = Effect.fnUntraced(function* (
|
||||
toolName: string,
|
||||
@@ -167,12 +158,7 @@ function permissionTitle(toolName: string, input: ToolInput, previews: ReadonlyA
|
||||
}
|
||||
}
|
||||
|
||||
function permissionLocations(
|
||||
toolName: string,
|
||||
input: ToolInput,
|
||||
ask: PermissionEvent["data"],
|
||||
cwd: string,
|
||||
): ToolCallLocation[] {
|
||||
function permissionLocations(toolName: string, input: ToolInput, ask: PermissionEvent["data"], cwd: string) {
|
||||
const locations = toLocations(toolName, input, cwd)
|
||||
if (locations.length > 0 || !PathActions.has(ask.action)) return locations
|
||||
const paths = ask.resources.flatMap((resource) => {
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import type { SessionUpdate } from "@agentclientprotocol/sdk"
|
||||
import type { OpenCodeClient } from "@opencode/client/effect"
|
||||
import type { SessionMessage } from "@opencode/schema/session-message"
|
||||
import { Effect, Option, Stream } from "effect"
|
||||
import type { Capabilities } from "./capabilities"
|
||||
import { ACPClient } from "./client"
|
||||
import { ACPCompaction } from "./compaction"
|
||||
import type { ACPConnection } from "./connection"
|
||||
import { partsToContentChunks } from "./content"
|
||||
import type { Attached } from "./sessions"
|
||||
import { ACPTranslate } from "./translate"
|
||||
import { completedToolUpdate, errorToolUpdate, pendingToolCall, runningToolUpdate } from "./tool"
|
||||
|
||||
export function history(
|
||||
client: OpenCodeClient,
|
||||
connection: ACPConnection.Interface,
|
||||
attached: Attached,
|
||||
capabilities: Capabilities,
|
||||
) {
|
||||
return Stream.paginate(undefined, (cursor: string | undefined) =>
|
||||
(cursor
|
||||
? client.message.list({ sessionID: attached.id, limit: 200, cursor })
|
||||
: client.message.list({ sessionID: attached.id, limit: 200, order: "asc" })
|
||||
).pipe(
|
||||
Effect.catch(ACPClient.classify),
|
||||
Effect.map((page) => [page.data, Option.fromNullishOr(page.cursor.next)] as const),
|
||||
),
|
||||
).pipe(
|
||||
Stream.runForEach((message) =>
|
||||
Effect.forEach(
|
||||
updates(message, attached.cwd, capabilities),
|
||||
(update) => connection.sessionUpdate({ sessionId: attached.id, update }),
|
||||
{ discard: true },
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
export function updates(message: SessionMessage.Info, cwd: string, capabilities: Capabilities): SessionUpdate[] {
|
||||
if (message.type === "user")
|
||||
return [
|
||||
{ sessionUpdate: "user_message_chunk", messageId: message.id, content: { type: "text", text: message.text } },
|
||||
...partsToContentChunks(
|
||||
(message.files ?? []).map((file) => ({
|
||||
type: "file",
|
||||
url: file.source.type === "uri" ? file.source.uri : `data:${file.mime};base64,${file.data}`,
|
||||
filename: file.name,
|
||||
mime: file.mime,
|
||||
})),
|
||||
).map((chunk) => ({ sessionUpdate: "user_message_chunk" as const, messageId: message.id, ...chunk })),
|
||||
]
|
||||
if (message.type === "compaction") {
|
||||
const update = ACPCompaction.replay(message, capabilities.compaction)
|
||||
return update ? [update] : []
|
||||
}
|
||||
if (message.type !== "assistant") return []
|
||||
// Live reasoning ordinals count only reasoning parts, not the mixed content array.
|
||||
const reasoning = message.content.filter((part) => part.type === "reasoning")
|
||||
return message.content.flatMap((part): SessionUpdate[] => {
|
||||
if (part.type === "text")
|
||||
return [
|
||||
{ sessionUpdate: "agent_message_chunk", messageId: message.id, content: { type: "text", text: part.text } },
|
||||
]
|
||||
if (part.type === "reasoning")
|
||||
return [
|
||||
{
|
||||
sessionUpdate: "agent_thought_chunk",
|
||||
messageId: ACPTranslate.reasoningMessageID(message.id, reasoning.indexOf(part)),
|
||||
content: { type: "text", text: part.text },
|
||||
},
|
||||
]
|
||||
const call: SessionUpdate = {
|
||||
sessionUpdate: "tool_call",
|
||||
...pendingToolCall({
|
||||
toolCallId: part.id,
|
||||
toolName: part.name,
|
||||
state: { input: part.state.status === "streaming" ? {} : part.state.input },
|
||||
cwd,
|
||||
}),
|
||||
}
|
||||
switch (part.state.status) {
|
||||
case "completed":
|
||||
return [
|
||||
call,
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
...completedToolUpdate({
|
||||
toolCallId: part.id,
|
||||
toolName: part.name,
|
||||
input: part.state.input,
|
||||
metadata: part.state.metadata,
|
||||
content: part.state.content,
|
||||
cwd,
|
||||
}),
|
||||
},
|
||||
]
|
||||
case "running":
|
||||
return [
|
||||
call,
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
...runningToolUpdate({ toolCallId: part.id, toolName: part.name, state: { input: part.state.input }, cwd }),
|
||||
},
|
||||
]
|
||||
case "error":
|
||||
return [
|
||||
call,
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
...errorToolUpdate({
|
||||
toolCallId: part.id,
|
||||
toolName: part.name,
|
||||
input: part.state.input,
|
||||
metadata: part.state.metadata,
|
||||
content: part.state.content,
|
||||
error: part.state.error.message,
|
||||
cwd,
|
||||
}),
|
||||
},
|
||||
]
|
||||
case "streaming":
|
||||
return [call]
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export * as ACPReplay from "./replay"
|
||||
@@ -3,7 +3,7 @@ import { SessionsCursor } from "@opencode/protocol/groups/session"
|
||||
import { Model } from "@opencode/schema/model"
|
||||
import { AbsolutePath } from "@opencode/schema/schema"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
import { DateTime, Effect, Option, Ref, Schema, Stream } from "effect"
|
||||
import { DateTime, Effect, Ref, Schema } from "effect"
|
||||
import { withTimestampedFallback } from "@opencode/util/session-title-fallback"
|
||||
import type {
|
||||
AuthenticateRequest,
|
||||
@@ -27,7 +27,6 @@ import type {
|
||||
NewSessionResponse,
|
||||
PromptRequest,
|
||||
PromptResponse,
|
||||
RequestError,
|
||||
ResumeSessionRequest,
|
||||
ResumeSessionResponse,
|
||||
SetSessionConfigOptionRequest,
|
||||
@@ -36,41 +35,34 @@ import type {
|
||||
SetSessionModeResponse,
|
||||
} from "@agentclientprotocol/sdk"
|
||||
import { OPENCODE_VERSION } from "../version"
|
||||
import { ACPCapabilities, type Capabilities } from "./capabilities"
|
||||
import type { ACPCatalog, Catalog } from "./catalog"
|
||||
import { ACPClient } from "./client"
|
||||
import { configOptions, currentModel, DEFAULT_VARIANT_VALUE, parseModelSelection } from "./config-option"
|
||||
import type { ACPConnection } from "./connection"
|
||||
import { ACPDirectories } from "./directories"
|
||||
import { ACPError } from "./error"
|
||||
import { ACPReplay } from "./replay"
|
||||
import type { ACPSessions, Attached, SupportedMcpServer } from "./sessions"
|
||||
import { ACPTranslate } from "./translate"
|
||||
import type { ACPTurn } from "./turn"
|
||||
|
||||
export const AuthMethodID = "opencode-login"
|
||||
|
||||
export type Failure = ACPError.Error | RequestError | ACPCatalog.Error
|
||||
|
||||
export type Capabilities = {
|
||||
readonly childSessionUpdates: boolean
|
||||
readonly formElicitation: boolean
|
||||
readonly compaction: boolean
|
||||
}
|
||||
const AuthMethodID = "opencode-login"
|
||||
|
||||
export interface Interface {
|
||||
readonly initialize: (input: InitializeRequest) => Effect.Effect<InitializeResponse>
|
||||
readonly authenticate: (input: AuthenticateRequest) => Effect.Effect<AuthenticateResponse, Failure>
|
||||
readonly newSession: (input: NewSessionRequest) => Effect.Effect<NewSessionResponse, Failure>
|
||||
readonly loadSession: (input: LoadSessionRequest) => Effect.Effect<LoadSessionResponse, Failure>
|
||||
readonly listSessions: (input: ListSessionsRequest) => Effect.Effect<ListSessionsResponse, Failure>
|
||||
readonly deleteSession: (input: DeleteSessionRequest) => Effect.Effect<DeleteSessionResponse, Failure>
|
||||
readonly resumeSession: (input: ResumeSessionRequest) => Effect.Effect<ResumeSessionResponse, Failure>
|
||||
readonly closeSession: (input: CloseSessionRequest) => Effect.Effect<CloseSessionResponse, Failure>
|
||||
readonly forkSession: (input: ForkSessionRequest) => Effect.Effect<ForkSessionResponse, Failure>
|
||||
readonly authenticate: (input: AuthenticateRequest) => Effect.Effect<AuthenticateResponse, ACPError.Failure>
|
||||
readonly newSession: (input: NewSessionRequest) => Effect.Effect<NewSessionResponse, ACPError.Failure>
|
||||
readonly loadSession: (input: LoadSessionRequest) => Effect.Effect<LoadSessionResponse, ACPError.Failure>
|
||||
readonly listSessions: (input: ListSessionsRequest) => Effect.Effect<ListSessionsResponse, ACPError.Failure>
|
||||
readonly deleteSession: (input: DeleteSessionRequest) => Effect.Effect<DeleteSessionResponse, ACPError.Failure>
|
||||
readonly resumeSession: (input: ResumeSessionRequest) => Effect.Effect<ResumeSessionResponse, ACPError.Failure>
|
||||
readonly closeSession: (input: CloseSessionRequest) => Effect.Effect<CloseSessionResponse, ACPError.Failure>
|
||||
readonly forkSession: (input: ForkSessionRequest) => Effect.Effect<ForkSessionResponse, ACPError.Failure>
|
||||
readonly setSessionConfigOption: (
|
||||
input: SetSessionConfigOptionRequest,
|
||||
) => Effect.Effect<SetSessionConfigOptionResponse, Failure>
|
||||
readonly setSessionMode: (input: SetSessionModeRequest) => Effect.Effect<SetSessionModeResponse, Failure>
|
||||
readonly prompt: (input: PromptRequest, signal: AbortSignal) => Effect.Effect<PromptResponse, Failure>
|
||||
) => Effect.Effect<SetSessionConfigOptionResponse, ACPError.Failure>
|
||||
readonly setSessionMode: (input: SetSessionModeRequest) => Effect.Effect<SetSessionModeResponse, ACPError.Failure>
|
||||
readonly prompt: (input: PromptRequest, signal: AbortSignal) => Effect.Effect<PromptResponse, ACPError.Failure>
|
||||
readonly cancel: (input: CancelNotification) => Effect.Effect<void>
|
||||
}
|
||||
|
||||
@@ -86,7 +78,7 @@ export function make(input: {
|
||||
return configOptions(yield* input.catalog.get(attached.cwd), yield* Ref.get(attached.selection))
|
||||
})
|
||||
|
||||
const withReload = <A>(attached: Attached, select: Effect.Effect<A, Failure>) => {
|
||||
const withReload = <A>(attached: Attached, select: Effect.Effect<A, ACPError.Failure>) => {
|
||||
const retry = () => input.catalog.reload(attached.cwd).pipe(Effect.andThen(select))
|
||||
return select.pipe(
|
||||
Effect.catchTags({ ACPInvalidModelError: retry, ACPInvalidModeError: retry, ACPInvalidEffortError: retry }),
|
||||
@@ -132,36 +124,9 @@ export function make(input: {
|
||||
return session
|
||||
})
|
||||
|
||||
const replay = Effect.fnUntraced(function* (attached: Attached) {
|
||||
const capabilities = yield* Ref.get(input.capabilities)
|
||||
yield* Stream.paginate(undefined, (cursor: string | undefined) =>
|
||||
(cursor
|
||||
? input.client.message.list({ sessionID: attached.id, limit: 200, cursor })
|
||||
: input.client.message.list({ sessionID: attached.id, limit: 200, order: "asc" })
|
||||
).pipe(
|
||||
Effect.catch(ACPClient.classify),
|
||||
Effect.map((page) => [page.data, Option.fromNullishOr(page.cursor.next)] as const),
|
||||
),
|
||||
).pipe(
|
||||
Stream.runForEach((message) =>
|
||||
Effect.forEach(
|
||||
ACPTranslate.replayMessage(message, attached.cwd, capabilities),
|
||||
(update) => input.connection.sessionUpdate({ sessionId: attached.id, update }),
|
||||
{ discard: true },
|
||||
),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
initialize: Effect.fnUntraced(function* (params) {
|
||||
const elicitation = params.clientCapabilities?.elicitation
|
||||
const compaction = params.clientCapabilities?.session?.compaction
|
||||
yield* Ref.set(input.capabilities, {
|
||||
childSessionUpdates: params.clientCapabilities?._meta?.[ACPTranslate.ChildSessionUpdatesCapability] === true,
|
||||
formElicitation: elicitation?.form !== undefined && elicitation.form !== null,
|
||||
compaction: compaction !== undefined && compaction !== null,
|
||||
})
|
||||
yield* Ref.set(input.capabilities, ACPCapabilities.parse(params.clientCapabilities))
|
||||
const authMethod: AuthMethod = {
|
||||
description: "Run `opencode auth login` in the terminal",
|
||||
name: "Login with opencode",
|
||||
@@ -179,7 +144,7 @@ export function make(input: {
|
||||
mcpCapabilities: { http: true, sse: false },
|
||||
promptCapabilities: { embeddedContext: true, image: true },
|
||||
sessionCapabilities: { additionalDirectories: {}, close: {}, delete: {}, fork: {}, list: {}, resume: {} },
|
||||
_meta: { [ACPTranslate.ChildSessionUpdatesCapability]: true },
|
||||
_meta: { [ACPCapabilities.ChildSessionUpdates]: true },
|
||||
},
|
||||
authMethods: [authMethod],
|
||||
agentInfo: { name: "OpenCode", version: OPENCODE_VERSION },
|
||||
@@ -206,11 +171,16 @@ export function make(input: {
|
||||
const mcpServers = yield* supportedMcpServers(params.mcpServers)
|
||||
const session = yield* getSession(params.sessionId, params.cwd)
|
||||
yield* ACPDirectories.activate(input.client, session, directories)
|
||||
const attached = (yield* input.sessions.attach(session, session.location.directory, mcpServers)).attached
|
||||
return yield* replay(attached).pipe(
|
||||
Effect.andThen(currentOptions(attached)),
|
||||
const attachment = yield* input.sessions.attach(session, session.location.directory, mcpServers)
|
||||
return yield* ACPReplay.history(
|
||||
input.client,
|
||||
input.connection,
|
||||
attachment.attached,
|
||||
yield* Ref.get(input.capabilities),
|
||||
).pipe(
|
||||
Effect.andThen(currentOptions(attachment.attached)),
|
||||
Effect.map((configOptions) => ({ configOptions })),
|
||||
Effect.onError(() => input.sessions.release(attached)),
|
||||
Effect.onError(() => input.sessions.release(attachment.attached)),
|
||||
)
|
||||
}),
|
||||
listSessions: Effect.fnUntraced(function* (params) {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { isDeepStrictEqual } from "node:util"
|
||||
import type { McpServer, RequestError, SessionConfigOption } from "@agentclientprotocol/sdk"
|
||||
import type { McpServer, SessionConfigOption } from "@agentclientprotocol/sdk"
|
||||
import type { OpenCodeClient, OpenCodeEvent } from "@opencode/client/effect"
|
||||
import { Mcp } from "@opencode/schema/mcp"
|
||||
import type { Session } from "@opencode/schema/session"
|
||||
import { Cause, Context, Deferred, Effect, Exit, Queue, Ref, Scope, Stream } from "effect"
|
||||
import { Cause, Deferred, Effect, Exit, Queue, Ref, Scope, Stream } from "effect"
|
||||
import type { ACPCatalog, Catalog } from "./catalog"
|
||||
import { ACPClient } from "./client"
|
||||
import { availableCommands, configOptions, type Selection } from "./config-option"
|
||||
@@ -23,18 +23,13 @@ export interface Interface {
|
||||
session: Session.Info,
|
||||
cwd: string,
|
||||
mcpServers: readonly SupportedMcpServer[],
|
||||
) => Effect.Effect<
|
||||
{ readonly attached: Attached; readonly configOptions: SessionConfigOption[] },
|
||||
ACPError.Error | RequestError | ACPCatalog.Error
|
||||
>
|
||||
) => Effect.Effect<{ readonly attached: Attached; readonly configOptions: SessionConfigOption[] }, ACPError.Failure>
|
||||
readonly detach: (sessionID: string) => Effect.Effect<void>
|
||||
readonly release: (attached: Attached) => Effect.Effect<void>
|
||||
readonly require: (sessionID: string) => Effect.Effect<Attached, ACPError.SessionNotFoundError>
|
||||
readonly fork: (attached: Attached, effect: Effect.Effect<void>) => Effect.Effect<void, ACPError.SessionNotFoundError>
|
||||
}
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/cli/acp/Sessions") {}
|
||||
|
||||
type Entry = {
|
||||
readonly attached: Attached
|
||||
readonly scope: Scope.Closeable
|
||||
@@ -51,7 +46,7 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
const scope = yield* Effect.scope
|
||||
const sessions = new Map<string, Entry>()
|
||||
// Outlives entries so re-attaching does not re-add servers.
|
||||
const registeredMcp = new Map<string, Set<string>>()
|
||||
const registeredMcpBySession = new Map<string, Map<string, Mcp.ServerConfig>>()
|
||||
const connected = yield* Deferred.make<void>()
|
||||
|
||||
// Subscribe before any attach so a switch right after `sessions.set` reaches the session.
|
||||
@@ -96,19 +91,18 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
|
||||
const registerMcp = (attached: Attached, servers: readonly SupportedMcpServer[]) =>
|
||||
Effect.suspend(() => {
|
||||
const registered = registeredMcp.get(attached.id) ?? new Set<string>()
|
||||
registeredMcp.set(attached.id, registered)
|
||||
const registered = registeredMcpBySession.get(attached.id) ?? new Map<string, Mcp.ServerConfig>()
|
||||
registeredMcpBySession.set(attached.id, registered)
|
||||
return Effect.forEach(
|
||||
servers,
|
||||
(server) =>
|
||||
Effect.suspend(() => {
|
||||
const config = mcpConfig(server)
|
||||
const key = `${server.name}:${stableStringify(config)}`
|
||||
if (registered.has(key)) return Effect.void
|
||||
registered.add(key)
|
||||
if (isDeepStrictEqual(registered.get(server.name), config)) return Effect.void
|
||||
registered.set(server.name, config)
|
||||
return input.client.mcp.add({ server: server.name, location: { directory: attached.cwd }, config }).pipe(
|
||||
Effect.catch(ACPClient.classify),
|
||||
Effect.onError(() => Effect.sync(() => registered.delete(key))),
|
||||
Effect.onError(() => Effect.sync(() => registered.delete(server.name))),
|
||||
Effect.uninterruptible,
|
||||
)
|
||||
}),
|
||||
@@ -120,12 +114,12 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
Effect.suspend(() => {
|
||||
if (sessions.get(sessionID) === entry) {
|
||||
sessions.delete(sessionID)
|
||||
registeredMcp.delete(sessionID)
|
||||
registeredMcpBySession.delete(sessionID)
|
||||
}
|
||||
return Scope.close(entry.scope, Exit.void)
|
||||
})
|
||||
|
||||
return Service.of({
|
||||
return {
|
||||
attach: Effect.fn("cli.acp.sessions.attach")(function* (session, cwd, mcpServers) {
|
||||
yield* Deferred.await(connected)
|
||||
const current = yield* input.catalog.get(cwd)
|
||||
@@ -175,7 +169,7 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
const entry = sessions.get(attached.id)
|
||||
if (entry?.attached === attached) yield* remove(attached.id, entry)
|
||||
}),
|
||||
require: Effect.fn("cli.acp.sessions.require")(function* (sessionID) {
|
||||
require: Effect.fnUntraced(function* (sessionID) {
|
||||
const entry = sessions.get(sessionID)
|
||||
if (!entry) return yield* new ACPError.SessionNotFoundError({ sessionId: sessionID })
|
||||
return entry.attached
|
||||
@@ -185,7 +179,7 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
if (entry?.attached !== attached) return yield* new ACPError.SessionNotFoundError({ sessionId: attached.id })
|
||||
yield* Effect.forkIn(effect, entry.scope, { startImmediately: true })
|
||||
}),
|
||||
})
|
||||
} satisfies Interface
|
||||
})
|
||||
|
||||
function mcpConfig(server: SupportedMcpServer) {
|
||||
@@ -204,13 +198,4 @@ function mcpConfig(server: SupportedMcpServer) {
|
||||
})
|
||||
}
|
||||
|
||||
function stableStringify(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`
|
||||
if (!value || typeof value !== "object") return JSON.stringify(value)
|
||||
return `{${Object.entries(value)
|
||||
.toSorted(([a], [b]) => a.localeCompare(b))
|
||||
.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`)
|
||||
.join(",")}}`
|
||||
}
|
||||
|
||||
export * as ACPSessions from "./sessions"
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import { isAbsolute, resolve } from "node:path"
|
||||
import type { ToolCall, ToolCallContent, ToolCallLocation, ToolCallUpdate, ToolKind } from "@agentclientprotocol/sdk"
|
||||
import type { Tool } from "@opencode/schema/tool"
|
||||
import { readDisplayText } from "@opencode/tui/mini/tool"
|
||||
import { Patch } from "@opencode/util/patch"
|
||||
import { Result } from "effect"
|
||||
|
||||
export type ToolInput = Record<string, unknown>
|
||||
export type ToolContent = ReadonlyArray<
|
||||
| { readonly type: "text"; readonly text: string }
|
||||
| { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string | null }
|
||||
>
|
||||
|
||||
export function toToolKind(toolName: string): ToolKind {
|
||||
function toToolKind(toolName: string): ToolKind {
|
||||
switch (toolName.toLocaleLowerCase()) {
|
||||
case "bash":
|
||||
case "shell":
|
||||
@@ -85,18 +82,16 @@ export function pendingToolCall(input: {
|
||||
export function runningToolUpdate(input: {
|
||||
readonly toolCallId: string
|
||||
readonly toolName: string
|
||||
readonly state: { readonly input: ToolInput; readonly title?: string }
|
||||
readonly content?: ToolContent
|
||||
readonly state: { readonly input: ToolInput }
|
||||
readonly cwd: string
|
||||
}): ToolCallUpdate {
|
||||
return {
|
||||
toolCallId: input.toolCallId,
|
||||
status: "in_progress",
|
||||
kind: toToolKind(input.toolName),
|
||||
title: toolTitle(input.toolName, input.state.input, input.state.title),
|
||||
title: toolTitle(input.toolName, input.state.input),
|
||||
locations: toLocations(input.toolName, input.state.input, input.cwd),
|
||||
rawInput: rawInput(input.toolName, input.state.input, input.cwd),
|
||||
...(input.content?.length ? { content: toolContent(input.content) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +99,7 @@ export function completedToolUpdate(input: {
|
||||
readonly toolCallId: string
|
||||
readonly toolName: string
|
||||
readonly input: ToolInput
|
||||
readonly content: ToolContent
|
||||
readonly content: ReadonlyArray<Tool.Content>
|
||||
readonly metadata?: Readonly<Record<string, unknown>>
|
||||
readonly cwd: string
|
||||
}): ToolCallUpdate {
|
||||
@@ -138,7 +133,7 @@ export function errorToolUpdate(input: {
|
||||
readonly toolCallId: string
|
||||
readonly toolName: string
|
||||
readonly input: ToolInput
|
||||
readonly content?: ToolContent
|
||||
readonly content?: ReadonlyArray<Tool.Content>
|
||||
readonly metadata?: Readonly<Record<string, unknown>>
|
||||
readonly error: string
|
||||
readonly cwd: string
|
||||
@@ -147,7 +142,7 @@ export function errorToolUpdate(input: {
|
||||
toolCallId: input.toolCallId,
|
||||
status: "failed",
|
||||
kind: toToolKind(input.toolName),
|
||||
title: toolTitle(input.toolName, input.input, undefined),
|
||||
title: toolTitle(input.toolName, input.input),
|
||||
locations: toLocations(input.toolName, input.input, input.cwd),
|
||||
rawInput: rawInput(input.toolName, input.input, input.cwd),
|
||||
content: [...toolContent(input.content ?? []), { type: "content", content: { type: "text", text: input.error } }],
|
||||
@@ -158,7 +153,7 @@ export function errorToolUpdate(input: {
|
||||
}
|
||||
}
|
||||
|
||||
function toolContent(content: ToolContent): ToolCallContent[] {
|
||||
function toolContent(content: ReadonlyArray<Tool.Content>): ToolCallContent[] {
|
||||
return content.flatMap((part): ToolCallContent[] => {
|
||||
if (part.type === "text") return [{ type: "content", content: { type: "text", text: part.text } }]
|
||||
const match = /^data:([^;,]+)(?:;[^,]*)*;base64,(.*)$/.exec(part.uri)
|
||||
@@ -167,7 +162,7 @@ function toolContent(content: ToolContent): ToolCallContent[] {
|
||||
})
|
||||
}
|
||||
|
||||
function toolTitle(toolName: string, input: ToolInput, fallback: string | undefined) {
|
||||
function toolTitle(toolName: string, input: ToolInput, fallback?: string) {
|
||||
if (isShell(toolName)) return stringValue(input.command) ?? stringValue(input.cmd) ?? fallback ?? toolName
|
||||
return fallback || toolName
|
||||
}
|
||||
@@ -208,5 +203,3 @@ export function absolutePath(path: string, cwd: string) {
|
||||
export function stringValue(value: unknown) {
|
||||
return typeof value === "string" ? value : undefined
|
||||
}
|
||||
|
||||
export * as ACPTool from "./tool"
|
||||
|
||||
@@ -4,14 +4,11 @@ import type { Session } from "@opencode/schema/session"
|
||||
import type { SessionError } from "@opencode/schema/session-error"
|
||||
import type { SessionMessage } from "@opencode/schema/session-message"
|
||||
import { TokenUsage } from "@opencode/schema/token-usage"
|
||||
import { ACPChild } from "./child"
|
||||
import { ACPCompaction } from "./compaction"
|
||||
import { partsToContentChunks, type ReplayPart } from "./content"
|
||||
import { ACPError } from "./error"
|
||||
import type { ACPService } from "./service"
|
||||
import { completedToolUpdate, errorToolUpdate, pendingToolCall, runningToolUpdate, type ToolInput } from "./tool"
|
||||
|
||||
export const ChildSessionUpdatesCapability = "opencode/child-session-updates"
|
||||
export const ChildSessionUpdateMethod = "opencode/session/child_update"
|
||||
const RetryMeta = "opencode/retry"
|
||||
|
||||
export type TurnStart = { readonly type: "input" | "compaction"; readonly id: SessionMessage.ID }
|
||||
@@ -42,35 +39,12 @@ type RetryStatus = {
|
||||
readonly error: SessionError.Error
|
||||
}
|
||||
|
||||
export type ChildSession = {
|
||||
readonly id: string
|
||||
readonly parentID: string
|
||||
readonly depth: number
|
||||
readonly title?: string
|
||||
}
|
||||
|
||||
type ChildSessionEvent =
|
||||
| { readonly type: "update"; readonly update: SessionUpdate }
|
||||
| {
|
||||
readonly type: "status"
|
||||
readonly status: "created" | "running" | "completed" | "failed" | "interrupted"
|
||||
readonly error?: { readonly type: string; readonly message: string }
|
||||
}
|
||||
|
||||
export type ChildSessionUpdate = {
|
||||
readonly rootSessionId: string
|
||||
readonly childSessionId: string
|
||||
readonly parentSessionId: string
|
||||
readonly depth: number
|
||||
readonly title?: string
|
||||
} & ChildSessionEvent
|
||||
|
||||
export type TurnState = {
|
||||
readonly started: boolean
|
||||
readonly tools: ReadonlyMap<string, Tool>
|
||||
readonly retries: ReadonlyMap<string, RetryStatus>
|
||||
readonly compactions: ACPCompaction.Tracked
|
||||
readonly children: ReadonlyMap<string, ChildSession>
|
||||
readonly children: ReadonlyMap<string, ACPChild.Session>
|
||||
readonly openChildren: ReadonlySet<string>
|
||||
readonly asks: ReadonlySet<string>
|
||||
readonly finish?: SessionMessage.Assistant["finish"]
|
||||
@@ -84,22 +58,22 @@ type FormEvent = Extract<OpenCodeEvent, { type: "form.created" }>
|
||||
|
||||
export type Output =
|
||||
| { readonly _tag: "SessionUpdate"; readonly update: SessionUpdate }
|
||||
| { readonly _tag: "ChildUpdate"; readonly update: ChildSessionUpdate }
|
||||
| { readonly _tag: "ChildUpdate"; readonly update: ACPChild.Update }
|
||||
| {
|
||||
readonly _tag: "PermissionAsk"
|
||||
readonly event: PermissionEvent
|
||||
readonly tool?: Tool
|
||||
readonly child?: ChildSession
|
||||
readonly child?: ACPChild.Session
|
||||
}
|
||||
| {
|
||||
readonly _tag: "FormAsk"
|
||||
readonly form: FormEvent["data"]["form"]
|
||||
readonly child?: ChildSession
|
||||
readonly child?: ACPChild.Session
|
||||
readonly toolCallSent: boolean
|
||||
}
|
||||
| { readonly _tag: "AskSettled"; readonly id: string }
|
||||
|
||||
export type Step = {
|
||||
type Step = {
|
||||
readonly state: TurnState
|
||||
readonly outputs: ReadonlyArray<Output>
|
||||
readonly terminal?: Terminal
|
||||
@@ -171,7 +145,8 @@ export function step(state: TurnState, event: OpenCodeEvent, ctx: Context): Step
|
||||
return { state: { ...state, asks }, outputs: [{ _tag: "AskSettled", id: settledID }] }
|
||||
}
|
||||
if (!eventSessionID || (eventSessionID !== ctx.sessionID && !child)) return { state, outputs: [] }
|
||||
if (matchesStart(event, ctx.start)) return { state: { ...state, started: true }, outputs: [] }
|
||||
if (event.type === "session.inbox.delivered" && event.data.inboxID === ctx.start.id)
|
||||
return { state: { ...state, started: true }, outputs: [] }
|
||||
if (!state.started) return { state, outputs: [] }
|
||||
|
||||
switch (event.type) {
|
||||
@@ -228,7 +203,7 @@ export function step(state: TurnState, event: OpenCodeEvent, ctx: Context): Step
|
||||
state,
|
||||
outputs: send({
|
||||
sessionUpdate: "agent_thought_chunk",
|
||||
messageId: `${event.data.assistantMessageID}:reasoning:${event.data.ordinal}`,
|
||||
messageId: reasoningMessageID(event.data.assistantMessageID, event.data.ordinal),
|
||||
content: { type: "text", text: event.data.delta },
|
||||
}),
|
||||
}
|
||||
@@ -405,126 +380,31 @@ export function abandon(state: TurnState, ctx: Context): Step {
|
||||
}
|
||||
}
|
||||
|
||||
export function* replayMessage(
|
||||
message: SessionMessage.Info,
|
||||
cwd: string,
|
||||
capabilities: ACPService.Capabilities,
|
||||
): Generator<SessionUpdate> {
|
||||
if (message.type === "user") {
|
||||
yield { sessionUpdate: "user_message_chunk", messageId: message.id, content: { type: "text", text: message.text } }
|
||||
const files: ReplayPart[] = (message.files ?? []).map((file) => ({
|
||||
type: "file",
|
||||
url: file.source.type === "uri" ? file.source.uri : `data:${file.mime};base64,${file.data}`,
|
||||
filename: file.name,
|
||||
mime: file.mime,
|
||||
}))
|
||||
for (const chunk of partsToContentChunks(files))
|
||||
yield { sessionUpdate: "user_message_chunk", messageId: message.id, ...chunk }
|
||||
return
|
||||
}
|
||||
if (message.type === "compaction") {
|
||||
const update = ACPCompaction.replay(message, capabilities.compaction)
|
||||
if (update) yield update
|
||||
return
|
||||
}
|
||||
if (message.type !== "assistant") return
|
||||
// Live reasoning ordinals count only reasoning parts, not the mixed content array.
|
||||
let reasoningOrdinal = 0
|
||||
for (const part of message.content) {
|
||||
if (part.type === "text") {
|
||||
yield { sessionUpdate: "agent_message_chunk", messageId: message.id, content: { type: "text", text: part.text } }
|
||||
continue
|
||||
}
|
||||
if (part.type === "reasoning") {
|
||||
yield {
|
||||
sessionUpdate: "agent_thought_chunk",
|
||||
messageId: `${message.id}:reasoning:${reasoningOrdinal++}`,
|
||||
content: { type: "text", text: part.text },
|
||||
}
|
||||
continue
|
||||
}
|
||||
yield {
|
||||
sessionUpdate: "tool_call",
|
||||
...pendingToolCall({
|
||||
toolCallId: part.id,
|
||||
toolName: part.name,
|
||||
state: { input: part.state.status === "streaming" ? {} : part.state.input },
|
||||
cwd,
|
||||
}),
|
||||
}
|
||||
switch (part.state.status) {
|
||||
case "completed":
|
||||
yield {
|
||||
sessionUpdate: "tool_call_update",
|
||||
...completedToolUpdate({
|
||||
toolCallId: part.id,
|
||||
toolName: part.name,
|
||||
input: part.state.input,
|
||||
metadata: part.state.metadata,
|
||||
content: part.state.content,
|
||||
cwd,
|
||||
}),
|
||||
}
|
||||
break
|
||||
case "running":
|
||||
yield {
|
||||
sessionUpdate: "tool_call_update",
|
||||
...runningToolUpdate({ toolCallId: part.id, toolName: part.name, state: { input: part.state.input }, cwd }),
|
||||
}
|
||||
break
|
||||
case "error":
|
||||
yield {
|
||||
sessionUpdate: "tool_call_update",
|
||||
...errorToolUpdate({
|
||||
toolCallId: part.id,
|
||||
toolName: part.name,
|
||||
input: part.state.input,
|
||||
metadata: part.state.metadata,
|
||||
content: part.state.content,
|
||||
error: part.state.error.message,
|
||||
cwd,
|
||||
}),
|
||||
}
|
||||
break
|
||||
case "streaming":
|
||||
break
|
||||
}
|
||||
}
|
||||
export function reasoningMessageID(messageID: string, ordinal: number) {
|
||||
return `${messageID}:reasoning:${ordinal}`
|
||||
}
|
||||
|
||||
function newTool(sessionID: string, id: string, name = "tool"): Tool {
|
||||
return { sessionID, id, name, input: {}, metadata: {} }
|
||||
}
|
||||
|
||||
function route(ctx: Context, child: ChildSession | undefined, update: SessionUpdate): Output[] {
|
||||
function route(ctx: Context, child: ACPChild.Session | undefined, update: SessionUpdate): Output[] {
|
||||
if (!child) return ctx.mode === "turn" ? [{ _tag: "SessionUpdate", update }] : []
|
||||
const projected = projectChildUpdate(update, child)
|
||||
const projected = ACPChild.project(update, child)
|
||||
if (ctx.childUpdates) return childStatus(ctx, child, { type: "update", update: projected })
|
||||
return ctx.mode === "turn" ? [{ _tag: "SessionUpdate", update: projected }] : []
|
||||
}
|
||||
|
||||
function childStatus(ctx: Context, child: ChildSession, value: ChildSessionEvent): Output[] {
|
||||
function childStatus(ctx: Context, child: ACPChild.Session, event: ACPChild.Event): Output[] {
|
||||
if (!ctx.childUpdates) return []
|
||||
return [
|
||||
{
|
||||
_tag: "ChildUpdate",
|
||||
update: {
|
||||
rootSessionId: ctx.sessionID,
|
||||
childSessionId: child.id,
|
||||
parentSessionId: child.parentID,
|
||||
depth: child.depth,
|
||||
...(child.title ? { title: child.title } : {}),
|
||||
...value,
|
||||
},
|
||||
},
|
||||
]
|
||||
return [{ _tag: "ChildUpdate", update: ACPChild.update(ctx.sessionID, child, event) }]
|
||||
}
|
||||
|
||||
function childEnded(
|
||||
state: TurnState,
|
||||
ctx: Context,
|
||||
child: ChildSession,
|
||||
status: ChildSessionEvent,
|
||||
child: ACPChild.Session,
|
||||
status: ACPChild.Event,
|
||||
terminal: Terminal,
|
||||
): Step {
|
||||
const openChildren = new Set(state.openChildren)
|
||||
@@ -570,31 +450,6 @@ function toolKey(sessionID: string, id: string) {
|
||||
return `${sessionID}:${id}`
|
||||
}
|
||||
|
||||
function projectChildUpdate(update: SessionUpdate, child: ChildSession) {
|
||||
const projected = { ...update }
|
||||
projected._meta = { ...projected._meta, ...childSessionMeta(child) }
|
||||
if (projected.sessionUpdate === "tool_call" || projected.sessionUpdate === "tool_call_update") {
|
||||
projected.toolCallId = `${child.id}:${projected.toolCallId}`
|
||||
if (projected.title && child.title) projected.title = `${child.title}: ${projected.title}`
|
||||
}
|
||||
return projected
|
||||
}
|
||||
|
||||
export function childSessionMeta(child: ChildSession) {
|
||||
return {
|
||||
"opencode/child-session": {
|
||||
id: child.id,
|
||||
parentID: child.parentID,
|
||||
depth: child.depth,
|
||||
...(child.title ? { title: child.title } : {}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function matchesStart(event: OpenCodeEvent, start: TurnStart) {
|
||||
return event.type === "session.inbox.delivered" && event.data.inboxID === start.id
|
||||
}
|
||||
|
||||
function resolveStopReason(input: {
|
||||
readonly terminal: Terminal
|
||||
readonly finish: SessionMessage.Assistant["finish"]
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { CancelNotification, PromptRequest, PromptResponse, RequestError } from "@agentclientprotocol/sdk"
|
||||
import type { OpenCodeClient, OpenCodeEvent } from "@opencode/client/effect"
|
||||
import type { Command } from "@opencode/schema/command"
|
||||
import type { Session } from "@opencode/schema/session"
|
||||
import { SessionMessage } from "@opencode/schema/session-message"
|
||||
import { TokenUsage } from "@opencode/schema/token-usage"
|
||||
import {
|
||||
@@ -21,7 +20,9 @@ import {
|
||||
} from "effect"
|
||||
import { access, constants } from "node:fs/promises"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import type { Capabilities } from "./capabilities"
|
||||
import { builtinCommands, type ACPCatalog, type Catalog } from "./catalog"
|
||||
import { ACPChild } from "./child"
|
||||
import { ACPClient } from "./client"
|
||||
import { currentModel } from "./config-option"
|
||||
import type { ACPConnection } from "./connection"
|
||||
@@ -29,21 +30,16 @@ import { linkReference, promptContentToParts, type PromptPart } from "./content"
|
||||
import { ACPElicitation } from "./elicitation"
|
||||
import { ACPError } from "./error"
|
||||
import { ACPPermission } from "./permission"
|
||||
import type { ACPService } from "./service"
|
||||
import type { ACPSessions, Attached } from "./sessions"
|
||||
import { ACPTranslate } from "./translate"
|
||||
|
||||
type Failure = ACPError.Error | RequestError | ACPCatalog.Error
|
||||
|
||||
export interface Interface {
|
||||
readonly prompt: (input: PromptRequest, signal: AbortSignal) => Effect.Effect<PromptResponse, Failure>
|
||||
readonly prompt: (input: PromptRequest, signal: AbortSignal) => Effect.Effect<PromptResponse, ACPError.Failure>
|
||||
readonly cancel: (input: CancelNotification) => Effect.Effect<void>
|
||||
/** Unlike `cancel`, interrupts an idle session too, since server work can outlive its turn. */
|
||||
readonly close: (sessionID: string) => Effect.Effect<void, ACPError.Error | RequestError>
|
||||
}
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/cli/acp/Turn") {}
|
||||
|
||||
/** Core acknowledges an interrupt before its cleanup settles, and its shell tool waits 3s before SIGKILL. */
|
||||
export const CancelDrainTimeout = Context.Reference<Duration.Input>("@opencode/cli/acp/Turn/CancelDrainTimeout", {
|
||||
defaultValue: () => "5 seconds",
|
||||
@@ -74,11 +70,11 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
readonly connection: ACPConnection.Interface
|
||||
readonly sessions: ACPSessions.Interface
|
||||
readonly catalog: ACPCatalog.Interface
|
||||
readonly capabilities: Ref.Ref<ACPService.Capabilities>
|
||||
readonly capabilities: Ref.Ref<Capabilities>
|
||||
}) {
|
||||
const scope = yield* Effect.scope
|
||||
const drainTimeout = yield* CancelDrainTimeout
|
||||
const turns = yield* FiberMap.make<string, PromptResponse, Failure>()
|
||||
const turns = yield* FiberMap.make<string, PromptResponse, ACPError.Failure>()
|
||||
|
||||
const subscribe = Effect.fnUntraced(function* () {
|
||||
// Parented to the service scope; the session scope may already be closed.
|
||||
@@ -143,7 +139,7 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
return input.connection.sessionUpdate({ sessionId: ctx.sessionID, update: output.update })
|
||||
case "ChildUpdate":
|
||||
return input.connection
|
||||
.extNotification(ACPTranslate.ChildSessionUpdateMethod, output.update)
|
||||
.extNotification(ACPChild.UpdateMethod, output.update)
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
@@ -244,23 +240,20 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
.pipe(Effect.catch(ACPClient.classify))
|
||||
})
|
||||
|
||||
const interruptServer = (sessionID: Session.ID) =>
|
||||
input.client.session
|
||||
.interrupt({ sessionID })
|
||||
const windDown = Effect.fnUntraced(function* (
|
||||
subscription: Subscription,
|
||||
ctx: ACPTranslate.Context,
|
||||
state: Ref.Ref<ACPTranslate.TurnState>,
|
||||
events: Fiber.Fiber<ACPTranslate.Terminal, ACPError.Failure>,
|
||||
) {
|
||||
yield* Deferred.succeed(subscription.cancelled, undefined)
|
||||
yield* input.client.session
|
||||
.interrupt({ sessionID: ctx.sessionID })
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause) ? Effect.void : Effect.logWarning("ACP server interrupt failed", cause),
|
||||
),
|
||||
)
|
||||
|
||||
const windDown = Effect.fnUntraced(function* (
|
||||
subscription: Subscription,
|
||||
ctx: ACPTranslate.Context,
|
||||
state: Ref.Ref<ACPTranslate.TurnState>,
|
||||
events: Fiber.Fiber<ACPTranslate.Terminal, Failure>,
|
||||
) {
|
||||
yield* Deferred.succeed(subscription.cancelled, undefined)
|
||||
yield* interruptServer(ctx.sessionID)
|
||||
if (!(yield* Ref.get(state)).started) return
|
||||
if (Option.exists(yield* Fiber.await(events).pipe(Effect.timeoutOption(drainTimeout)), Exit.isSuccess)) return
|
||||
yield* Fiber.interrupt(events)
|
||||
@@ -300,7 +293,7 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
subscription: Subscription,
|
||||
ctx: ACPTranslate.Context,
|
||||
state: Ref.Ref<ACPTranslate.TurnState>,
|
||||
exit: Exit.Exit<ACPTranslate.Terminal, Failure>,
|
||||
exit: Exit.Exit<ACPTranslate.Terminal, ACPError.Failure>,
|
||||
) {
|
||||
const close = Scope.close(subscription.scope, Exit.void)
|
||||
if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) return yield* close
|
||||
@@ -318,7 +311,7 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
const settle = Effect.fnUntraced(function* (
|
||||
attached: Attached,
|
||||
state: Ref.Ref<ACPTranslate.TurnState>,
|
||||
exit: Exit.Exit<ACPTranslate.Terminal, Failure>,
|
||||
exit: Exit.Exit<ACPTranslate.Terminal, ACPError.Failure>,
|
||||
) {
|
||||
if (Exit.isFailure(exit) && !Cause.hasInterrupts(exit.cause)) return yield* Effect.failCause(exit.cause)
|
||||
const current = yield* Ref.get(state)
|
||||
@@ -368,8 +361,8 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
return yield* settle(attached, state, exit)
|
||||
})
|
||||
|
||||
return Service.of({
|
||||
prompt: Effect.fn("cli.acp.turn.prompt")(function* (params, signal) {
|
||||
return {
|
||||
prompt: Effect.fnUntraced(function* (params, signal) {
|
||||
const attached = yield* input.sessions.require(params.sessionId)
|
||||
const catalog = yield* input.catalog.get(attached.cwd)
|
||||
if (params.prompt.some((block) => block.type === "image" && !block.data && !block.uri)) {
|
||||
@@ -397,7 +390,7 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
yield* aborted(signal).pipe(Effect.andThen(Fiber.interrupt(turn)), Effect.forkChild)
|
||||
return yield* Fiber.join(turn)
|
||||
}),
|
||||
cancel: Effect.fn("cli.acp.turn.cancel")(function* (params) {
|
||||
cancel: Effect.fnUntraced(function* (params) {
|
||||
yield* FiberMap.remove(turns, params.sessionId)
|
||||
}),
|
||||
close: Effect.fn("cli.acp.turn.close")(function* (sessionID) {
|
||||
@@ -408,7 +401,7 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
Effect.catch(ACPClient.classify),
|
||||
)
|
||||
}),
|
||||
})
|
||||
} satisfies Interface
|
||||
})
|
||||
|
||||
function aborted(signal: AbortSignal) {
|
||||
@@ -427,8 +420,17 @@ function preparePrompt(catalog: Catalog, parts: readonly PromptPart[], messageID
|
||||
const files = visible.flatMap((part) => (part.type === "file" ? [{ uri: part.url, name: part.filename }] : []))
|
||||
const slash = detectSlashCommand(text)
|
||||
const command = slash ? catalog.commands.find((item) => item.name === slash.name) : undefined
|
||||
const start = turnStart(messageID, slash)
|
||||
return { start, text, files, synthetic, slash, command }
|
||||
return {
|
||||
start:
|
||||
slash && builtinCommands.get(slash.name)?.start === "compaction"
|
||||
? { type: "compaction", id: messageID }
|
||||
: { type: "input", id: messageID },
|
||||
text,
|
||||
files,
|
||||
synthetic,
|
||||
slash,
|
||||
command,
|
||||
}
|
||||
}
|
||||
|
||||
function referenceUnreadableFile(part: PromptPart) {
|
||||
@@ -439,12 +441,7 @@ function referenceUnreadableFile(part: PromptPart) {
|
||||
)
|
||||
}
|
||||
|
||||
function turnStart(messageID: SessionMessage.ID, slash: PreparedPrompt["slash"]): ACPTranslate.TurnStart {
|
||||
if (slash && builtinCommands.get(slash.name)?.start === "compaction") return { type: "compaction", id: messageID }
|
||||
return { type: "input", id: messageID }
|
||||
}
|
||||
|
||||
function detectSlashCommand(text: string): { readonly name: string; readonly args: string } | undefined {
|
||||
function detectSlashCommand(text: string) {
|
||||
const value = text.trim()
|
||||
if (!value.startsWith("/")) return undefined
|
||||
const [name, ...rest] = value.slice(1).split(/\s+/)
|
||||
|
||||
@@ -137,19 +137,28 @@ describe("acp session lifecycle over the wire", () => {
|
||||
const first = await acp.newSession("/workspace", [local, local, remote])
|
||||
await acp.request("session/resume", { cwd: "/workspace", sessionId: first.sessionId, mcpServers: [local, remote] })
|
||||
await acp.request("session/resume", { cwd: "/workspace", sessionId: first.sessionId, mcpServers: [changed] })
|
||||
await acp.newSession("/workspace", [local])
|
||||
await acp.request("session/resume", { cwd: "/workspace", sessionId: first.sessionId, mcpServers: [local] })
|
||||
|
||||
const localConfig = (args: string[]) => ({
|
||||
name: "tools",
|
||||
directory: "/workspace",
|
||||
config: { type: "local", command: ["bun", ...args], environment: { TOKEN: "x" } },
|
||||
})
|
||||
expect(acp.server.mcp).toHaveLength(4)
|
||||
expect(acp.server.mcp.filter((item) => item.name === "tools")).toEqual([
|
||||
localConfig(["server.ts"]),
|
||||
localConfig(["changed.ts"]),
|
||||
localConfig(["server.ts"]),
|
||||
])
|
||||
|
||||
await acp.newSession("/workspace", [local])
|
||||
|
||||
expect(acp.server.mcp).toHaveLength(5)
|
||||
expect(acp.server.mcp.filter((item) => item.name === "tools")).toEqual([
|
||||
localConfig(["server.ts"]),
|
||||
localConfig(["changed.ts"]),
|
||||
localConfig(["server.ts"]),
|
||||
localConfig(["server.ts"]),
|
||||
])
|
||||
expect(acp.server.mcp.find((item) => item.name === "docs")).toEqual({
|
||||
name: "docs",
|
||||
directory: "/workspace",
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Session } from "@opencode/schema/session"
|
||||
import { SessionMessage } from "@opencode/schema/session-message"
|
||||
import { Schema } from "effect"
|
||||
import path from "node:path"
|
||||
import { ACPReplay } from "../../src/acp/replay"
|
||||
import { ACPTranslate } from "../../src/acp/translate"
|
||||
import {
|
||||
assistantMessage,
|
||||
@@ -629,7 +630,7 @@ function translate(row: Row) {
|
||||
}
|
||||
return {
|
||||
updates: row.messages.flatMap((message) => [
|
||||
...ACPTranslate.replayMessage(decodeMessage(message), context.cwd, capabilities),
|
||||
...ACPReplay.updates(decodeMessage(message), context.cwd, capabilities),
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user