| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127 |
- import {
- RequestError,
- type Agent as ACPAgent,
- type AgentSideConnection,
- type AuthenticateRequest,
- type AuthMethod,
- type CancelNotification,
- type InitializeRequest,
- type InitializeResponse,
- type LoadSessionRequest,
- type NewSessionRequest,
- type PermissionOption,
- type PlanEntry,
- type PromptRequest,
- type SetSessionModelRequest,
- type SetSessionModeRequest,
- type SetSessionModeResponse,
- type ToolCallContent,
- type ToolKind,
- } from "@agentclientprotocol/sdk"
- import { Log } from "../util/log"
- import { ACPSessionManager } from "./session"
- import type { ACPConfig, ACPSessionState } from "./types"
- import { Provider } from "../provider/provider"
- import { Agent as AgentModule } from "../agent/agent"
- import { Installation } from "@/installation"
- import { MessageV2 } from "@/session/message-v2"
- import { Config } from "@/config/config"
- import { Todo } from "@/session/todo"
- import { z } from "zod"
- import { LoadAPIKeyError } from "ai"
- import type { OpencodeClient, SessionMessageResponse } from "@opencode-ai/sdk/v2"
- import { applyPatch } from "diff"
- export namespace ACP {
- const log = Log.create({ service: "acp-agent" })
- export async function init({ sdk: _sdk }: { sdk: OpencodeClient }) {
- return {
- create: (connection: AgentSideConnection, fullConfig: ACPConfig) => {
- return new Agent(connection, fullConfig)
- },
- }
- }
- export class Agent implements ACPAgent {
- private connection: AgentSideConnection
- private config: ACPConfig
- private sdk: OpencodeClient
- private sessionManager
- constructor(connection: AgentSideConnection, config: ACPConfig) {
- this.connection = connection
- this.config = config
- this.sdk = config.sdk
- this.sessionManager = new ACPSessionManager(this.sdk)
- }
- private setupEventSubscriptions(session: ACPSessionState) {
- const sessionId = session.id
- const directory = session.cwd
- const options: PermissionOption[] = [
- { optionId: "once", kind: "allow_once", name: "Allow once" },
- { optionId: "always", kind: "allow_always", name: "Always allow" },
- { optionId: "reject", kind: "reject_once", name: "Reject" },
- ]
- this.config.sdk.event.subscribe({ directory }).then(async (events) => {
- for await (const event of events.stream) {
- switch (event.type) {
- case "permission.asked":
- try {
- const permission = event.properties
- const res = await this.connection
- .requestPermission({
- sessionId,
- toolCall: {
- toolCallId: permission.tool?.callID ?? permission.id,
- status: "pending",
- title: permission.permission,
- rawInput: permission.metadata,
- kind: toToolKind(permission.permission),
- locations: toLocations(permission.permission, permission.metadata),
- },
- options,
- })
- .catch(async (error) => {
- log.error("failed to request permission from ACP", {
- error,
- permissionID: permission.id,
- sessionID: permission.sessionID,
- })
- await this.config.sdk.permission.reply({
- requestID: permission.id,
- reply: "reject",
- directory,
- })
- return
- })
- if (!res) return
- if (res.outcome.outcome !== "selected") {
- await this.config.sdk.permission.reply({
- requestID: permission.id,
- reply: "reject",
- directory,
- })
- return
- }
- if (res.outcome.optionId !== "reject" && permission.permission == "edit") {
- const metadata = permission.metadata || {}
- const filepath = typeof metadata["filepath"] === "string" ? metadata["filepath"] : ""
- const diff = typeof metadata["diff"] === "string" ? metadata["diff"] : ""
- const content = await Bun.file(filepath).text()
- const newContent = getNewContent(content, diff)
- if (newContent) {
- this.connection.writeTextFile({
- sessionId: sessionId,
- path: filepath,
- content: newContent,
- })
- }
- }
- await this.config.sdk.permission.reply({
- requestID: permission.id,
- reply: res.outcome.optionId as "once" | "always" | "reject",
- directory,
- })
- } catch (err) {
- log.error("unexpected error when handling permission", { error: err })
- } finally {
- break
- }
- case "message.part.updated":
- log.info("message part updated", { event: event.properties })
- try {
- const props = event.properties
- const { part } = props
- const message = await this.config.sdk.session
- .message(
- {
- sessionID: part.sessionID,
- messageID: part.messageID,
- directory,
- },
- { throwOnError: true },
- )
- .then((x) => x.data)
- .catch((err) => {
- log.error("unexpected error when fetching message", { error: err })
- return undefined
- })
- if (!message || message.info.role !== "assistant") return
- if (part.type === "tool") {
- switch (part.state.status) {
- case "pending":
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "tool_call",
- toolCallId: part.callID,
- title: part.tool,
- kind: toToolKind(part.tool),
- status: "pending",
- locations: [],
- rawInput: {},
- },
- })
- .catch((err) => {
- log.error("failed to send tool pending to ACP", { error: err })
- })
- break
- case "running":
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: part.callID,
- status: "in_progress",
- kind: toToolKind(part.tool),
- title: part.tool,
- locations: toLocations(part.tool, part.state.input),
- rawInput: part.state.input,
- },
- })
- .catch((err) => {
- log.error("failed to send tool in_progress to ACP", { error: err })
- })
- break
- case "completed":
- const kind = toToolKind(part.tool)
- const content: ToolCallContent[] = [
- {
- type: "content",
- content: {
- type: "text",
- text: part.state.output,
- },
- },
- ]
- if (kind === "edit") {
- const input = part.state.input
- const filePath = typeof input["filePath"] === "string" ? input["filePath"] : ""
- const oldText = typeof input["oldString"] === "string" ? input["oldString"] : ""
- const newText =
- typeof input["newString"] === "string"
- ? input["newString"]
- : typeof input["content"] === "string"
- ? input["content"]
- : ""
- content.push({
- type: "diff",
- path: filePath,
- oldText,
- newText,
- })
- }
- if (part.tool === "todowrite") {
- const parsedTodos = z.array(Todo.Info).safeParse(JSON.parse(part.state.output))
- if (parsedTodos.success) {
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "plan",
- entries: parsedTodos.data.map((todo) => {
- const status: PlanEntry["status"] =
- todo.status === "cancelled" ? "completed" : (todo.status as PlanEntry["status"])
- return {
- priority: "medium",
- status,
- content: todo.content,
- }
- }),
- },
- })
- .catch((err) => {
- log.error("failed to send session update for todo", { error: err })
- })
- } else {
- log.error("failed to parse todo output", { error: parsedTodos.error })
- }
- }
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: part.callID,
- status: "completed",
- kind,
- content,
- title: part.state.title,
- rawInput: part.state.input,
- rawOutput: {
- output: part.state.output,
- metadata: part.state.metadata,
- },
- },
- })
- .catch((err) => {
- log.error("failed to send tool completed to ACP", { error: err })
- })
- break
- case "error":
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: part.callID,
- status: "failed",
- kind: toToolKind(part.tool),
- title: part.tool,
- rawInput: part.state.input,
- content: [
- {
- type: "content",
- content: {
- type: "text",
- text: part.state.error,
- },
- },
- ],
- rawOutput: {
- error: part.state.error,
- },
- },
- })
- .catch((err) => {
- log.error("failed to send tool error to ACP", { error: err })
- })
- break
- }
- } else if (part.type === "text") {
- const delta = props.delta
- if (delta && part.synthetic !== true) {
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "agent_message_chunk",
- content: {
- type: "text",
- text: delta,
- },
- },
- })
- .catch((err) => {
- log.error("failed to send text to ACP", { error: err })
- })
- }
- } else if (part.type === "reasoning") {
- const delta = props.delta
- if (delta) {
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "agent_thought_chunk",
- content: {
- type: "text",
- text: delta,
- },
- },
- })
- .catch((err) => {
- log.error("failed to send reasoning to ACP", { error: err })
- })
- }
- }
- } finally {
- break
- }
- }
- }
- })
- }
- async initialize(params: InitializeRequest): Promise<InitializeResponse> {
- log.info("initialize", { protocolVersion: params.protocolVersion })
- const authMethod: AuthMethod = {
- description: "Run `opencode auth login` in the terminal",
- name: "Login with opencode",
- id: "opencode-login",
- }
- // If client supports terminal-auth capability, use that instead.
- if (params.clientCapabilities?._meta?.["terminal-auth"] === true) {
- authMethod._meta = {
- "terminal-auth": {
- command: "opencode",
- args: ["auth", "login"],
- label: "OpenCode Login",
- },
- }
- }
- return {
- protocolVersion: 1,
- agentCapabilities: {
- loadSession: true,
- mcpCapabilities: {
- http: true,
- sse: true,
- },
- promptCapabilities: {
- embeddedContext: true,
- image: true,
- },
- },
- authMethods: [authMethod],
- agentInfo: {
- name: "OpenCode",
- version: Installation.VERSION,
- },
- }
- }
- async authenticate(_params: AuthenticateRequest) {
- throw new Error("Authentication not implemented")
- }
- async newSession(params: NewSessionRequest) {
- const directory = params.cwd
- try {
- const model = await defaultModel(this.config, directory)
- // Store ACP session state
- const state = await this.sessionManager.create(params.cwd, params.mcpServers, model)
- const sessionId = state.id
- log.info("creating_session", { sessionId, mcpServers: params.mcpServers.length })
- const load = await this.loadSessionMode({
- cwd: directory,
- mcpServers: params.mcpServers,
- sessionId,
- })
- this.setupEventSubscriptions(state)
- return {
- sessionId,
- models: load.models,
- modes: load.modes,
- _meta: {},
- }
- } catch (e) {
- const error = MessageV2.fromError(e, {
- providerID: this.config.defaultModel?.providerID ?? "unknown",
- })
- if (LoadAPIKeyError.isInstance(error)) {
- throw RequestError.authRequired()
- }
- throw e
- }
- }
- async loadSession(params: LoadSessionRequest) {
- const directory = params.cwd
- const sessionId = params.sessionId
- try {
- const model = await defaultModel(this.config, directory)
- // Store ACP session state
- const state = await this.sessionManager.load(sessionId, params.cwd, params.mcpServers, model)
- log.info("load_session", { sessionId, mcpServers: params.mcpServers.length })
- const mode = await this.loadSessionMode({
- cwd: directory,
- mcpServers: params.mcpServers,
- sessionId,
- })
- this.setupEventSubscriptions(state)
- // Replay session history
- const messages = await this.sdk.session
- .messages(
- {
- sessionID: sessionId,
- directory,
- },
- { throwOnError: true },
- )
- .then((x) => x.data)
- .catch((err) => {
- log.error("unexpected error when fetching message", { error: err })
- return undefined
- })
- for (const msg of messages ?? []) {
- log.debug("replay message", msg)
- await this.processMessage(msg)
- }
- return mode
- } catch (e) {
- const error = MessageV2.fromError(e, {
- providerID: this.config.defaultModel?.providerID ?? "unknown",
- })
- if (LoadAPIKeyError.isInstance(error)) {
- throw RequestError.authRequired()
- }
- throw e
- }
- }
- private async processMessage(message: SessionMessageResponse) {
- log.debug("process message", message)
- if (message.info.role !== "assistant" && message.info.role !== "user") return
- const sessionId = message.info.sessionID
- for (const part of message.parts) {
- if (part.type === "tool") {
- switch (part.state.status) {
- case "pending":
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "tool_call",
- toolCallId: part.callID,
- title: part.tool,
- kind: toToolKind(part.tool),
- status: "pending",
- locations: [],
- rawInput: {},
- },
- })
- .catch((err) => {
- log.error("failed to send tool pending to ACP", { error: err })
- })
- break
- case "running":
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: part.callID,
- status: "in_progress",
- kind: toToolKind(part.tool),
- title: part.tool,
- locations: toLocations(part.tool, part.state.input),
- rawInput: part.state.input,
- },
- })
- .catch((err) => {
- log.error("failed to send tool in_progress to ACP", { error: err })
- })
- break
- case "completed":
- const kind = toToolKind(part.tool)
- const content: ToolCallContent[] = [
- {
- type: "content",
- content: {
- type: "text",
- text: part.state.output,
- },
- },
- ]
- if (kind === "edit") {
- const input = part.state.input
- const filePath = typeof input["filePath"] === "string" ? input["filePath"] : ""
- const oldText = typeof input["oldString"] === "string" ? input["oldString"] : ""
- const newText =
- typeof input["newString"] === "string"
- ? input["newString"]
- : typeof input["content"] === "string"
- ? input["content"]
- : ""
- content.push({
- type: "diff",
- path: filePath,
- oldText,
- newText,
- })
- }
- if (part.tool === "todowrite") {
- const parsedTodos = z.array(Todo.Info).safeParse(JSON.parse(part.state.output))
- if (parsedTodos.success) {
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "plan",
- entries: parsedTodos.data.map((todo) => {
- const status: PlanEntry["status"] =
- todo.status === "cancelled" ? "completed" : (todo.status as PlanEntry["status"])
- return {
- priority: "medium",
- status,
- content: todo.content,
- }
- }),
- },
- })
- .catch((err) => {
- log.error("failed to send session update for todo", { error: err })
- })
- } else {
- log.error("failed to parse todo output", { error: parsedTodos.error })
- }
- }
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: part.callID,
- status: "completed",
- kind,
- content,
- title: part.state.title,
- rawInput: part.state.input,
- rawOutput: {
- output: part.state.output,
- metadata: part.state.metadata,
- },
- },
- })
- .catch((err) => {
- log.error("failed to send tool completed to ACP", { error: err })
- })
- break
- case "error":
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: part.callID,
- status: "failed",
- kind: toToolKind(part.tool),
- title: part.tool,
- rawInput: part.state.input,
- content: [
- {
- type: "content",
- content: {
- type: "text",
- text: part.state.error,
- },
- },
- ],
- rawOutput: {
- error: part.state.error,
- },
- },
- })
- .catch((err) => {
- log.error("failed to send tool error to ACP", { error: err })
- })
- break
- }
- } else if (part.type === "text") {
- if (part.text) {
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: message.info.role === "user" ? "user_message_chunk" : "agent_message_chunk",
- content: {
- type: "text",
- text: part.text,
- },
- },
- })
- .catch((err) => {
- log.error("failed to send text to ACP", { error: err })
- })
- }
- } else if (part.type === "reasoning") {
- if (part.text) {
- await this.connection
- .sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "agent_thought_chunk",
- content: {
- type: "text",
- text: part.text,
- },
- },
- })
- .catch((err) => {
- log.error("failed to send reasoning to ACP", { error: err })
- })
- }
- }
- }
- }
- private async loadSessionMode(params: LoadSessionRequest) {
- const directory = params.cwd
- const model = await defaultModel(this.config, directory)
- const sessionId = params.sessionId
- const providers = await this.sdk.config.providers({ directory }).then((x) => x.data!.providers)
- const entries = providers.sort((a, b) => {
- const nameA = a.name.toLowerCase()
- const nameB = b.name.toLowerCase()
- if (nameA < nameB) return -1
- if (nameA > nameB) return 1
- return 0
- })
- const availableModels = entries.flatMap((provider) => {
- const models = Provider.sort(Object.values(provider.models))
- return models.map((model) => ({
- modelId: `${provider.id}/${model.id}`,
- name: `${provider.name}/${model.name}`,
- }))
- })
- const agents = await this.config.sdk.app
- .agents(
- {
- directory,
- },
- { throwOnError: true },
- )
- .then((resp) => resp.data!)
- const commands = await this.config.sdk.command
- .list(
- {
- directory,
- },
- { throwOnError: true },
- )
- .then((resp) => resp.data!)
- const availableCommands = commands.map((command) => ({
- name: command.name,
- description: command.description ?? "",
- }))
- const names = new Set(availableCommands.map((c) => c.name))
- if (!names.has("compact"))
- availableCommands.push({
- name: "compact",
- description: "compact the session",
- })
- const availableModes = agents
- .filter((agent) => agent.mode !== "subagent" && !agent.hidden)
- .map((agent) => ({
- id: agent.name,
- name: agent.name,
- description: agent.description,
- }))
- const defaultAgentName = await AgentModule.defaultAgent()
- const currentModeId = availableModes.find((m) => m.name === defaultAgentName)?.id ?? availableModes[0].id
- // Persist the default mode so prompt() uses it immediately
- this.sessionManager.setMode(sessionId, currentModeId)
- const mcpServers: Record<string, Config.Mcp> = {}
- for (const server of params.mcpServers) {
- if ("type" in server) {
- mcpServers[server.name] = {
- url: server.url,
- headers: server.headers.reduce<Record<string, string>>((acc, { name, value }) => {
- acc[name] = value
- return acc
- }, {}),
- type: "remote",
- }
- } else {
- mcpServers[server.name] = {
- type: "local",
- command: [server.command, ...server.args],
- environment: server.env.reduce<Record<string, string>>((acc, { name, value }) => {
- acc[name] = value
- return acc
- }, {}),
- }
- }
- }
- await Promise.all(
- Object.entries(mcpServers).map(async ([key, mcp]) => {
- await this.sdk.mcp
- .add(
- {
- directory,
- name: key,
- config: mcp,
- },
- { throwOnError: true },
- )
- .catch((error) => {
- log.error("failed to add mcp server", { name: key, error })
- })
- }),
- )
- setTimeout(() => {
- this.connection.sessionUpdate({
- sessionId,
- update: {
- sessionUpdate: "available_commands_update",
- availableCommands,
- },
- })
- }, 0)
- return {
- sessionId,
- models: {
- currentModelId: `${model.providerID}/${model.modelID}`,
- availableModels,
- },
- modes: {
- availableModes,
- currentModeId,
- },
- _meta: {},
- }
- }
- async setSessionModel(params: SetSessionModelRequest) {
- const session = this.sessionManager.get(params.sessionId)
- const model = Provider.parseModel(params.modelId)
- this.sessionManager.setModel(session.id, {
- providerID: model.providerID,
- modelID: model.modelID,
- })
- return {
- _meta: {},
- }
- }
- async setSessionMode(params: SetSessionModeRequest): Promise<SetSessionModeResponse | void> {
- this.sessionManager.get(params.sessionId)
- await this.config.sdk.app
- .agents({}, { throwOnError: true })
- .then((x) => x.data)
- .then((agent) => {
- if (!agent) throw new Error(`Agent not found: ${params.modeId}`)
- })
- this.sessionManager.setMode(params.sessionId, params.modeId)
- }
- async prompt(params: PromptRequest) {
- const sessionID = params.sessionId
- const session = this.sessionManager.get(sessionID)
- const directory = session.cwd
- const current = session.model
- const model = current ?? (await defaultModel(this.config, directory))
- if (!current) {
- this.sessionManager.setModel(session.id, model)
- }
- const agent = session.modeId ?? (await AgentModule.defaultAgent())
- const parts: Array<
- { type: "text"; text: string } | { type: "file"; url: string; filename: string; mime: string }
- > = []
- for (const part of params.prompt) {
- switch (part.type) {
- case "text":
- parts.push({
- type: "text" as const,
- text: part.text,
- })
- break
- case "image":
- if (part.data) {
- parts.push({
- type: "file",
- url: `data:${part.mimeType};base64,${part.data}`,
- filename: "image",
- mime: part.mimeType,
- })
- } else if (part.uri && part.uri.startsWith("http:")) {
- parts.push({
- type: "file",
- url: part.uri,
- filename: "image",
- mime: part.mimeType,
- })
- }
- break
- case "resource_link":
- const parsed = parseUri(part.uri)
- parts.push(parsed)
- break
- case "resource":
- const resource = part.resource
- if ("text" in resource) {
- parts.push({
- type: "text",
- text: resource.text,
- })
- }
- break
- default:
- break
- }
- }
- log.info("parts", { parts })
- const cmd = (() => {
- const text = parts
- .filter((p): p is { type: "text"; text: string } => p.type === "text")
- .map((p) => p.text)
- .join("")
- .trim()
- if (!text.startsWith("/")) return
- const [name, ...rest] = text.slice(1).split(/\s+/)
- return { name, args: rest.join(" ").trim() }
- })()
- const done = {
- stopReason: "end_turn" as const,
- _meta: {},
- }
- if (!cmd) {
- await this.sdk.session.prompt({
- sessionID,
- model: {
- providerID: model.providerID,
- modelID: model.modelID,
- },
- parts,
- agent,
- directory,
- })
- return done
- }
- const command = await this.config.sdk.command
- .list({ directory }, { throwOnError: true })
- .then((x) => x.data!.find((c) => c.name === cmd.name))
- if (command) {
- await this.sdk.session.command({
- sessionID,
- command: command.name,
- arguments: cmd.args,
- model: model.providerID + "/" + model.modelID,
- agent,
- directory,
- })
- return done
- }
- switch (cmd.name) {
- case "compact":
- await this.config.sdk.session.summarize(
- {
- sessionID,
- directory,
- providerID: model.providerID,
- modelID: model.modelID,
- },
- { throwOnError: true },
- )
- break
- }
- return done
- }
- async cancel(params: CancelNotification) {
- const session = this.sessionManager.get(params.sessionId)
- await this.config.sdk.session.abort(
- {
- sessionID: params.sessionId,
- directory: session.cwd,
- },
- { throwOnError: true },
- )
- }
- }
- function toToolKind(toolName: string): ToolKind {
- const tool = toolName.toLocaleLowerCase()
- switch (tool) {
- case "bash":
- return "execute"
- case "webfetch":
- return "fetch"
- case "edit":
- case "patch":
- case "write":
- return "edit"
- case "grep":
- case "glob":
- case "context7_resolve_library_id":
- case "context7_get_library_docs":
- return "search"
- case "list":
- case "read":
- return "read"
- default:
- return "other"
- }
- }
- function toLocations(toolName: string, input: Record<string, any>): { path: string }[] {
- const tool = toolName.toLocaleLowerCase()
- switch (tool) {
- case "read":
- case "edit":
- case "write":
- return input["filePath"] ? [{ path: input["filePath"] }] : []
- case "glob":
- case "grep":
- return input["path"] ? [{ path: input["path"] }] : []
- case "bash":
- return []
- case "list":
- return input["path"] ? [{ path: input["path"] }] : []
- default:
- return []
- }
- }
- async function defaultModel(config: ACPConfig, cwd?: string) {
- const sdk = config.sdk
- const configured = config.defaultModel
- if (configured) return configured
- const directory = cwd ?? process.cwd()
- const specified = await sdk.config
- .get({ directory }, { throwOnError: true })
- .then((resp) => {
- const cfg = resp.data
- if (!cfg || !cfg.model) return undefined
- const parsed = Provider.parseModel(cfg.model)
- return {
- providerID: parsed.providerID,
- modelID: parsed.modelID,
- }
- })
- .catch((error) => {
- log.error("failed to load user config for default model", { error })
- return undefined
- })
- const providers = await sdk.config
- .providers({ directory }, { throwOnError: true })
- .then((x) => x.data?.providers ?? [])
- .catch((error) => {
- log.error("failed to list providers for default model", { error })
- return []
- })
- if (specified && providers.length) {
- const provider = providers.find((p) => p.id === specified.providerID)
- if (provider && provider.models[specified.modelID]) return specified
- }
- if (specified && !providers.length) return specified
- const opencodeProvider = providers.find((p) => p.id === "opencode")
- if (opencodeProvider) {
- if (opencodeProvider.models["big-pickle"]) {
- return { providerID: "opencode", modelID: "big-pickle" }
- }
- const [best] = Provider.sort(Object.values(opencodeProvider.models))
- if (best) {
- return {
- providerID: best.providerID,
- modelID: best.id,
- }
- }
- }
- const models = providers.flatMap((p) => Object.values(p.models))
- const [best] = Provider.sort(models)
- if (best) {
- return {
- providerID: best.providerID,
- modelID: best.id,
- }
- }
- if (specified) return specified
- return { providerID: "opencode", modelID: "big-pickle" }
- }
- function parseUri(
- uri: string,
- ): { type: "file"; url: string; filename: string; mime: string } | { type: "text"; text: string } {
- try {
- if (uri.startsWith("file://")) {
- const path = uri.slice(7)
- const name = path.split("/").pop() || path
- return {
- type: "file",
- url: uri,
- filename: name,
- mime: "text/plain",
- }
- }
- if (uri.startsWith("zed://")) {
- const url = new URL(uri)
- const path = url.searchParams.get("path")
- if (path) {
- const name = path.split("/").pop() || path
- return {
- type: "file",
- url: `file://${path}`,
- filename: name,
- mime: "text/plain",
- }
- }
- }
- return {
- type: "text",
- text: uri,
- }
- } catch {
- return {
- type: "text",
- text: uri,
- }
- }
- }
- function getNewContent(fileOriginal: string, unifiedDiff: string): string | undefined {
- const result = applyPatch(fileOriginal, unifiedDiff)
- if (result === false) {
- log.error("Failed to apply unified diff (context mismatch)")
- return undefined
- }
- return result
- }
- }
|