2
0

agent.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. import {
  2. RequestError,
  3. type Agent as ACPAgent,
  4. type AgentSideConnection,
  5. type AuthenticateRequest,
  6. type AuthMethod,
  7. type CancelNotification,
  8. type ForkSessionRequest,
  9. type ForkSessionResponse,
  10. type InitializeRequest,
  11. type InitializeResponse,
  12. type ListSessionsRequest,
  13. type ListSessionsResponse,
  14. type LoadSessionRequest,
  15. type NewSessionRequest,
  16. type PermissionOption,
  17. type PlanEntry,
  18. type PromptRequest,
  19. type ResumeSessionRequest,
  20. type ResumeSessionResponse,
  21. type Role,
  22. type SessionInfo,
  23. type SetSessionModelRequest,
  24. type SetSessionModeRequest,
  25. type SetSessionModeResponse,
  26. type ToolCallContent,
  27. type ToolKind,
  28. } from "@agentclientprotocol/sdk"
  29. import { Log } from "../util/log"
  30. import { ACPSessionManager } from "./session"
  31. import type { ACPConfig } from "./types"
  32. import { Provider } from "../provider/provider"
  33. import { Agent as AgentModule } from "../agent/agent"
  34. import { Installation } from "@/installation"
  35. import { MessageV2 } from "@/session/message-v2"
  36. import { Config } from "@/config/config"
  37. import { Todo } from "@/session/todo"
  38. import { z } from "zod"
  39. import { LoadAPIKeyError } from "ai"
  40. import type { Event, OpencodeClient, SessionMessageResponse } from "@opencode-ai/sdk/v2"
  41. import { applyPatch } from "diff"
  42. export namespace ACP {
  43. const log = Log.create({ service: "acp-agent" })
  44. export async function init({ sdk: _sdk }: { sdk: OpencodeClient }) {
  45. return {
  46. create: (connection: AgentSideConnection, fullConfig: ACPConfig) => {
  47. return new Agent(connection, fullConfig)
  48. },
  49. }
  50. }
  51. export class Agent implements ACPAgent {
  52. private connection: AgentSideConnection
  53. private config: ACPConfig
  54. private sdk: OpencodeClient
  55. private sessionManager: ACPSessionManager
  56. private eventAbort = new AbortController()
  57. private eventStarted = false
  58. private permissionQueues = new Map<string, Promise<void>>()
  59. private permissionOptions: PermissionOption[] = [
  60. { optionId: "once", kind: "allow_once", name: "Allow once" },
  61. { optionId: "always", kind: "allow_always", name: "Always allow" },
  62. { optionId: "reject", kind: "reject_once", name: "Reject" },
  63. ]
  64. constructor(connection: AgentSideConnection, config: ACPConfig) {
  65. this.connection = connection
  66. this.config = config
  67. this.sdk = config.sdk
  68. this.sessionManager = new ACPSessionManager(this.sdk)
  69. this.startEventSubscription()
  70. }
  71. private startEventSubscription() {
  72. if (this.eventStarted) return
  73. this.eventStarted = true
  74. this.runEventSubscription().catch((error) => {
  75. if (this.eventAbort.signal.aborted) return
  76. log.error("event subscription failed", { error })
  77. })
  78. }
  79. private async runEventSubscription() {
  80. while (true) {
  81. if (this.eventAbort.signal.aborted) return
  82. const events = await this.sdk.global.event({
  83. signal: this.eventAbort.signal,
  84. })
  85. for await (const event of events.stream) {
  86. if (this.eventAbort.signal.aborted) return
  87. const payload = (event as any)?.payload
  88. if (!payload) continue
  89. await this.handleEvent(payload as Event).catch((error) => {
  90. log.error("failed to handle event", { error, type: payload.type })
  91. })
  92. }
  93. }
  94. }
  95. private async handleEvent(event: Event) {
  96. switch (event.type) {
  97. case "permission.asked": {
  98. const permission = event.properties
  99. const session = this.sessionManager.tryGet(permission.sessionID)
  100. if (!session) return
  101. const prev = this.permissionQueues.get(permission.sessionID) ?? Promise.resolve()
  102. const next = prev
  103. .then(async () => {
  104. const directory = session.cwd
  105. const res = await this.connection
  106. .requestPermission({
  107. sessionId: permission.sessionID,
  108. toolCall: {
  109. toolCallId: permission.tool?.callID ?? permission.id,
  110. status: "pending",
  111. title: permission.permission,
  112. rawInput: permission.metadata,
  113. kind: toToolKind(permission.permission),
  114. locations: toLocations(permission.permission, permission.metadata),
  115. },
  116. options: this.permissionOptions,
  117. })
  118. .catch(async (error) => {
  119. log.error("failed to request permission from ACP", {
  120. error,
  121. permissionID: permission.id,
  122. sessionID: permission.sessionID,
  123. })
  124. await this.sdk.permission.reply({
  125. requestID: permission.id,
  126. reply: "reject",
  127. directory,
  128. })
  129. return undefined
  130. })
  131. if (!res) return
  132. if (res.outcome.outcome !== "selected") {
  133. await this.sdk.permission.reply({
  134. requestID: permission.id,
  135. reply: "reject",
  136. directory,
  137. })
  138. return
  139. }
  140. if (res.outcome.optionId !== "reject" && permission.permission == "edit") {
  141. const metadata = permission.metadata || {}
  142. const filepath = typeof metadata["filepath"] === "string" ? metadata["filepath"] : ""
  143. const diff = typeof metadata["diff"] === "string" ? metadata["diff"] : ""
  144. const content = await Bun.file(filepath).text()
  145. const newContent = getNewContent(content, diff)
  146. if (newContent) {
  147. this.connection.writeTextFile({
  148. sessionId: session.id,
  149. path: filepath,
  150. content: newContent,
  151. })
  152. }
  153. }
  154. await this.sdk.permission.reply({
  155. requestID: permission.id,
  156. reply: res.outcome.optionId as "once" | "always" | "reject",
  157. directory,
  158. })
  159. })
  160. .catch((error) => {
  161. log.error("failed to handle permission", { error, permissionID: permission.id })
  162. })
  163. .finally(() => {
  164. if (this.permissionQueues.get(permission.sessionID) === next) {
  165. this.permissionQueues.delete(permission.sessionID)
  166. }
  167. })
  168. this.permissionQueues.set(permission.sessionID, next)
  169. return
  170. }
  171. case "message.part.updated": {
  172. log.info("message part updated", { event: event.properties })
  173. const props = event.properties
  174. const part = props.part
  175. const session = this.sessionManager.tryGet(part.sessionID)
  176. if (!session) return
  177. const sessionId = session.id
  178. const directory = session.cwd
  179. const message = await this.sdk.session
  180. .message(
  181. {
  182. sessionID: part.sessionID,
  183. messageID: part.messageID,
  184. directory,
  185. },
  186. { throwOnError: true },
  187. )
  188. .then((x) => x.data)
  189. .catch((error) => {
  190. log.error("unexpected error when fetching message", { error })
  191. return undefined
  192. })
  193. if (!message || message.info.role !== "assistant") return
  194. if (part.type === "tool") {
  195. switch (part.state.status) {
  196. case "pending":
  197. await this.connection
  198. .sessionUpdate({
  199. sessionId,
  200. update: {
  201. sessionUpdate: "tool_call",
  202. toolCallId: part.callID,
  203. title: part.tool,
  204. kind: toToolKind(part.tool),
  205. status: "pending",
  206. locations: [],
  207. rawInput: {},
  208. },
  209. })
  210. .catch((error) => {
  211. log.error("failed to send tool pending to ACP", { error })
  212. })
  213. return
  214. case "running":
  215. await this.connection
  216. .sessionUpdate({
  217. sessionId,
  218. update: {
  219. sessionUpdate: "tool_call_update",
  220. toolCallId: part.callID,
  221. status: "in_progress",
  222. kind: toToolKind(part.tool),
  223. title: part.tool,
  224. locations: toLocations(part.tool, part.state.input),
  225. rawInput: part.state.input,
  226. },
  227. })
  228. .catch((error) => {
  229. log.error("failed to send tool in_progress to ACP", { error })
  230. })
  231. return
  232. case "completed": {
  233. const kind = toToolKind(part.tool)
  234. const content: ToolCallContent[] = [
  235. {
  236. type: "content",
  237. content: {
  238. type: "text",
  239. text: part.state.output,
  240. },
  241. },
  242. ]
  243. if (kind === "edit") {
  244. const input = part.state.input
  245. const filePath = typeof input["filePath"] === "string" ? input["filePath"] : ""
  246. const oldText = typeof input["oldString"] === "string" ? input["oldString"] : ""
  247. const newText =
  248. typeof input["newString"] === "string"
  249. ? input["newString"]
  250. : typeof input["content"] === "string"
  251. ? input["content"]
  252. : ""
  253. content.push({
  254. type: "diff",
  255. path: filePath,
  256. oldText,
  257. newText,
  258. })
  259. }
  260. if (part.tool === "todowrite") {
  261. const parsedTodos = z.array(Todo.Info).safeParse(JSON.parse(part.state.output))
  262. if (parsedTodos.success) {
  263. await this.connection
  264. .sessionUpdate({
  265. sessionId,
  266. update: {
  267. sessionUpdate: "plan",
  268. entries: parsedTodos.data.map((todo) => {
  269. const status: PlanEntry["status"] =
  270. todo.status === "cancelled" ? "completed" : (todo.status as PlanEntry["status"])
  271. return {
  272. priority: "medium",
  273. status,
  274. content: todo.content,
  275. }
  276. }),
  277. },
  278. })
  279. .catch((error) => {
  280. log.error("failed to send session update for todo", { error })
  281. })
  282. } else {
  283. log.error("failed to parse todo output", { error: parsedTodos.error })
  284. }
  285. }
  286. await this.connection
  287. .sessionUpdate({
  288. sessionId,
  289. update: {
  290. sessionUpdate: "tool_call_update",
  291. toolCallId: part.callID,
  292. status: "completed",
  293. kind,
  294. content,
  295. title: part.state.title,
  296. rawInput: part.state.input,
  297. rawOutput: {
  298. output: part.state.output,
  299. metadata: part.state.metadata,
  300. },
  301. },
  302. })
  303. .catch((error) => {
  304. log.error("failed to send tool completed to ACP", { error })
  305. })
  306. return
  307. }
  308. case "error":
  309. await this.connection
  310. .sessionUpdate({
  311. sessionId,
  312. update: {
  313. sessionUpdate: "tool_call_update",
  314. toolCallId: part.callID,
  315. status: "failed",
  316. kind: toToolKind(part.tool),
  317. title: part.tool,
  318. rawInput: part.state.input,
  319. content: [
  320. {
  321. type: "content",
  322. content: {
  323. type: "text",
  324. text: part.state.error,
  325. },
  326. },
  327. ],
  328. rawOutput: {
  329. error: part.state.error,
  330. },
  331. },
  332. })
  333. .catch((error) => {
  334. log.error("failed to send tool error to ACP", { error })
  335. })
  336. return
  337. }
  338. }
  339. if (part.type === "text") {
  340. const delta = props.delta
  341. if (delta && part.ignored !== true) {
  342. await this.connection
  343. .sessionUpdate({
  344. sessionId,
  345. update: {
  346. sessionUpdate: "agent_message_chunk",
  347. content: {
  348. type: "text",
  349. text: delta,
  350. },
  351. },
  352. })
  353. .catch((error) => {
  354. log.error("failed to send text to ACP", { error })
  355. })
  356. }
  357. return
  358. }
  359. if (part.type === "reasoning") {
  360. const delta = props.delta
  361. if (delta) {
  362. await this.connection
  363. .sessionUpdate({
  364. sessionId,
  365. update: {
  366. sessionUpdate: "agent_thought_chunk",
  367. content: {
  368. type: "text",
  369. text: delta,
  370. },
  371. },
  372. })
  373. .catch((error) => {
  374. log.error("failed to send reasoning to ACP", { error })
  375. })
  376. }
  377. }
  378. return
  379. }
  380. }
  381. }
  382. async initialize(params: InitializeRequest): Promise<InitializeResponse> {
  383. log.info("initialize", { protocolVersion: params.protocolVersion })
  384. const authMethod: AuthMethod = {
  385. description: "Run `opencode auth login` in the terminal",
  386. name: "Login with opencode",
  387. id: "opencode-login",
  388. }
  389. // If client supports terminal-auth capability, use that instead.
  390. if (params.clientCapabilities?._meta?.["terminal-auth"] === true) {
  391. authMethod._meta = {
  392. "terminal-auth": {
  393. command: "opencode",
  394. args: ["auth", "login"],
  395. label: "OpenCode Login",
  396. },
  397. }
  398. }
  399. return {
  400. protocolVersion: 1,
  401. agentCapabilities: {
  402. loadSession: true,
  403. mcpCapabilities: {
  404. http: true,
  405. sse: true,
  406. },
  407. promptCapabilities: {
  408. embeddedContext: true,
  409. image: true,
  410. },
  411. sessionCapabilities: {
  412. fork: {},
  413. list: {},
  414. resume: {},
  415. },
  416. },
  417. authMethods: [authMethod],
  418. agentInfo: {
  419. name: "OpenCode",
  420. version: Installation.VERSION,
  421. },
  422. }
  423. }
  424. async authenticate(_params: AuthenticateRequest) {
  425. throw new Error("Authentication not implemented")
  426. }
  427. async newSession(params: NewSessionRequest) {
  428. const directory = params.cwd
  429. try {
  430. const model = await defaultModel(this.config, directory)
  431. // Store ACP session state
  432. const state = await this.sessionManager.create(params.cwd, params.mcpServers, model)
  433. const sessionId = state.id
  434. log.info("creating_session", { sessionId, mcpServers: params.mcpServers.length })
  435. const load = await this.loadSessionMode({
  436. cwd: directory,
  437. mcpServers: params.mcpServers,
  438. sessionId,
  439. })
  440. return {
  441. sessionId,
  442. models: load.models,
  443. modes: load.modes,
  444. _meta: {},
  445. }
  446. } catch (e) {
  447. const error = MessageV2.fromError(e, {
  448. providerID: this.config.defaultModel?.providerID ?? "unknown",
  449. })
  450. if (LoadAPIKeyError.isInstance(error)) {
  451. throw RequestError.authRequired()
  452. }
  453. throw e
  454. }
  455. }
  456. async loadSession(params: LoadSessionRequest) {
  457. const directory = params.cwd
  458. const sessionId = params.sessionId
  459. try {
  460. const model = await defaultModel(this.config, directory)
  461. // Store ACP session state
  462. await this.sessionManager.load(sessionId, params.cwd, params.mcpServers, model)
  463. log.info("load_session", { sessionId, mcpServers: params.mcpServers.length })
  464. const result = await this.loadSessionMode({
  465. cwd: directory,
  466. mcpServers: params.mcpServers,
  467. sessionId,
  468. })
  469. // Replay session history
  470. const messages = await this.sdk.session
  471. .messages(
  472. {
  473. sessionID: sessionId,
  474. directory,
  475. },
  476. { throwOnError: true },
  477. )
  478. .then((x) => x.data)
  479. .catch((err) => {
  480. log.error("unexpected error when fetching message", { error: err })
  481. return undefined
  482. })
  483. const lastUser = messages?.findLast((m) => m.info.role === "user")?.info
  484. if (lastUser?.role === "user") {
  485. result.models.currentModelId = `${lastUser.model.providerID}/${lastUser.model.modelID}`
  486. this.sessionManager.setModel(sessionId, {
  487. providerID: lastUser.model.providerID,
  488. modelID: lastUser.model.modelID,
  489. })
  490. if (result.modes.availableModes.some((m) => m.id === lastUser.agent)) {
  491. result.modes.currentModeId = lastUser.agent
  492. this.sessionManager.setMode(sessionId, lastUser.agent)
  493. }
  494. }
  495. for (const msg of messages ?? []) {
  496. log.debug("replay message", msg)
  497. await this.processMessage(msg)
  498. }
  499. return result
  500. } catch (e) {
  501. const error = MessageV2.fromError(e, {
  502. providerID: this.config.defaultModel?.providerID ?? "unknown",
  503. })
  504. if (LoadAPIKeyError.isInstance(error)) {
  505. throw RequestError.authRequired()
  506. }
  507. throw e
  508. }
  509. }
  510. async unstable_listSessions(params: ListSessionsRequest): Promise<ListSessionsResponse> {
  511. try {
  512. const cursor = params.cursor ? Number(params.cursor) : undefined
  513. const limit = 100
  514. const sessions = await this.sdk.session
  515. .list(
  516. {
  517. directory: params.cwd ?? undefined,
  518. roots: true,
  519. },
  520. { throwOnError: true },
  521. )
  522. .then((x) => x.data ?? [])
  523. const sorted = sessions.toSorted((a, b) => b.time.updated - a.time.updated)
  524. const filtered = cursor ? sorted.filter((s) => s.time.updated < cursor) : sorted
  525. const page = filtered.slice(0, limit)
  526. const entries: SessionInfo[] = page.map((session) => ({
  527. sessionId: session.id,
  528. cwd: session.directory,
  529. title: session.title,
  530. updatedAt: new Date(session.time.updated).toISOString(),
  531. }))
  532. const last = page[page.length - 1]
  533. const next = filtered.length > limit && last ? String(last.time.updated) : undefined
  534. const response: ListSessionsResponse = {
  535. sessions: entries,
  536. }
  537. if (next) response.nextCursor = next
  538. return response
  539. } catch (e) {
  540. const error = MessageV2.fromError(e, {
  541. providerID: this.config.defaultModel?.providerID ?? "unknown",
  542. })
  543. if (LoadAPIKeyError.isInstance(error)) {
  544. throw RequestError.authRequired()
  545. }
  546. throw e
  547. }
  548. }
  549. async unstable_forkSession(params: ForkSessionRequest): Promise<ForkSessionResponse> {
  550. const directory = params.cwd
  551. const mcpServers = params.mcpServers ?? []
  552. try {
  553. const model = await defaultModel(this.config, directory)
  554. const forked = await this.sdk.session
  555. .fork(
  556. {
  557. sessionID: params.sessionId,
  558. directory,
  559. },
  560. { throwOnError: true },
  561. )
  562. .then((x) => x.data)
  563. if (!forked) {
  564. throw new Error("Fork session returned no data")
  565. }
  566. const sessionId = forked.id
  567. await this.sessionManager.load(sessionId, directory, mcpServers, model)
  568. log.info("fork_session", { sessionId, mcpServers: mcpServers.length })
  569. const mode = await this.loadSessionMode({
  570. cwd: directory,
  571. mcpServers,
  572. sessionId,
  573. })
  574. const messages = await this.sdk.session
  575. .messages(
  576. {
  577. sessionID: sessionId,
  578. directory,
  579. },
  580. { throwOnError: true },
  581. )
  582. .then((x) => x.data)
  583. .catch((err) => {
  584. log.error("unexpected error when fetching message", { error: err })
  585. return undefined
  586. })
  587. for (const msg of messages ?? []) {
  588. log.debug("replay message", msg)
  589. await this.processMessage(msg)
  590. }
  591. return mode
  592. } catch (e) {
  593. const error = MessageV2.fromError(e, {
  594. providerID: this.config.defaultModel?.providerID ?? "unknown",
  595. })
  596. if (LoadAPIKeyError.isInstance(error)) {
  597. throw RequestError.authRequired()
  598. }
  599. throw e
  600. }
  601. }
  602. async unstable_resumeSession(params: ResumeSessionRequest): Promise<ResumeSessionResponse> {
  603. const directory = params.cwd
  604. const sessionId = params.sessionId
  605. const mcpServers = params.mcpServers ?? []
  606. try {
  607. const model = await defaultModel(this.config, directory)
  608. await this.sessionManager.load(sessionId, directory, mcpServers, model)
  609. log.info("resume_session", { sessionId, mcpServers: mcpServers.length })
  610. return this.loadSessionMode({
  611. cwd: directory,
  612. mcpServers,
  613. sessionId,
  614. })
  615. } catch (e) {
  616. const error = MessageV2.fromError(e, {
  617. providerID: this.config.defaultModel?.providerID ?? "unknown",
  618. })
  619. if (LoadAPIKeyError.isInstance(error)) {
  620. throw RequestError.authRequired()
  621. }
  622. throw e
  623. }
  624. }
  625. private async processMessage(message: SessionMessageResponse) {
  626. log.debug("process message", message)
  627. if (message.info.role !== "assistant" && message.info.role !== "user") return
  628. const sessionId = message.info.sessionID
  629. for (const part of message.parts) {
  630. if (part.type === "tool") {
  631. switch (part.state.status) {
  632. case "pending":
  633. await this.connection
  634. .sessionUpdate({
  635. sessionId,
  636. update: {
  637. sessionUpdate: "tool_call",
  638. toolCallId: part.callID,
  639. title: part.tool,
  640. kind: toToolKind(part.tool),
  641. status: "pending",
  642. locations: [],
  643. rawInput: {},
  644. },
  645. })
  646. .catch((err) => {
  647. log.error("failed to send tool pending to ACP", { error: err })
  648. })
  649. break
  650. case "running":
  651. await this.connection
  652. .sessionUpdate({
  653. sessionId,
  654. update: {
  655. sessionUpdate: "tool_call_update",
  656. toolCallId: part.callID,
  657. status: "in_progress",
  658. kind: toToolKind(part.tool),
  659. title: part.tool,
  660. locations: toLocations(part.tool, part.state.input),
  661. rawInput: part.state.input,
  662. },
  663. })
  664. .catch((err) => {
  665. log.error("failed to send tool in_progress to ACP", { error: err })
  666. })
  667. break
  668. case "completed":
  669. const kind = toToolKind(part.tool)
  670. const content: ToolCallContent[] = [
  671. {
  672. type: "content",
  673. content: {
  674. type: "text",
  675. text: part.state.output,
  676. },
  677. },
  678. ]
  679. if (kind === "edit") {
  680. const input = part.state.input
  681. const filePath = typeof input["filePath"] === "string" ? input["filePath"] : ""
  682. const oldText = typeof input["oldString"] === "string" ? input["oldString"] : ""
  683. const newText =
  684. typeof input["newString"] === "string"
  685. ? input["newString"]
  686. : typeof input["content"] === "string"
  687. ? input["content"]
  688. : ""
  689. content.push({
  690. type: "diff",
  691. path: filePath,
  692. oldText,
  693. newText,
  694. })
  695. }
  696. if (part.tool === "todowrite") {
  697. const parsedTodos = z.array(Todo.Info).safeParse(JSON.parse(part.state.output))
  698. if (parsedTodos.success) {
  699. await this.connection
  700. .sessionUpdate({
  701. sessionId,
  702. update: {
  703. sessionUpdate: "plan",
  704. entries: parsedTodos.data.map((todo) => {
  705. const status: PlanEntry["status"] =
  706. todo.status === "cancelled" ? "completed" : (todo.status as PlanEntry["status"])
  707. return {
  708. priority: "medium",
  709. status,
  710. content: todo.content,
  711. }
  712. }),
  713. },
  714. })
  715. .catch((err) => {
  716. log.error("failed to send session update for todo", { error: err })
  717. })
  718. } else {
  719. log.error("failed to parse todo output", { error: parsedTodos.error })
  720. }
  721. }
  722. await this.connection
  723. .sessionUpdate({
  724. sessionId,
  725. update: {
  726. sessionUpdate: "tool_call_update",
  727. toolCallId: part.callID,
  728. status: "completed",
  729. kind,
  730. content,
  731. title: part.state.title,
  732. rawInput: part.state.input,
  733. rawOutput: {
  734. output: part.state.output,
  735. metadata: part.state.metadata,
  736. },
  737. },
  738. })
  739. .catch((err) => {
  740. log.error("failed to send tool completed to ACP", { error: err })
  741. })
  742. break
  743. case "error":
  744. await this.connection
  745. .sessionUpdate({
  746. sessionId,
  747. update: {
  748. sessionUpdate: "tool_call_update",
  749. toolCallId: part.callID,
  750. status: "failed",
  751. kind: toToolKind(part.tool),
  752. title: part.tool,
  753. rawInput: part.state.input,
  754. content: [
  755. {
  756. type: "content",
  757. content: {
  758. type: "text",
  759. text: part.state.error,
  760. },
  761. },
  762. ],
  763. rawOutput: {
  764. error: part.state.error,
  765. },
  766. },
  767. })
  768. .catch((err) => {
  769. log.error("failed to send tool error to ACP", { error: err })
  770. })
  771. break
  772. }
  773. } else if (part.type === "text") {
  774. if (part.text) {
  775. const audience: Role[] | undefined = part.synthetic ? ["assistant"] : part.ignored ? ["user"] : undefined
  776. await this.connection
  777. .sessionUpdate({
  778. sessionId,
  779. update: {
  780. sessionUpdate: message.info.role === "user" ? "user_message_chunk" : "agent_message_chunk",
  781. content: {
  782. type: "text",
  783. text: part.text,
  784. ...(audience && { annotations: { audience } }),
  785. },
  786. },
  787. })
  788. .catch((err) => {
  789. log.error("failed to send text to ACP", { error: err })
  790. })
  791. }
  792. } else if (part.type === "file") {
  793. // Replay file attachments as appropriate ACP content blocks.
  794. // OpenCode stores files internally as { type: "file", url, filename, mime }.
  795. // We convert these back to ACP blocks based on the URL scheme and MIME type:
  796. // - file:// URLs → resource_link
  797. // - data: URLs with image/* → image block
  798. // - data: URLs with text/* or application/json → resource with text
  799. // - data: URLs with other types → resource with blob
  800. const url = part.url
  801. const filename = part.filename ?? "file"
  802. const mime = part.mime || "application/octet-stream"
  803. const messageChunk = message.info.role === "user" ? "user_message_chunk" : "agent_message_chunk"
  804. if (url.startsWith("file://")) {
  805. // Local file reference - send as resource_link
  806. await this.connection
  807. .sessionUpdate({
  808. sessionId,
  809. update: {
  810. sessionUpdate: messageChunk,
  811. content: { type: "resource_link", uri: url, name: filename, mimeType: mime },
  812. },
  813. })
  814. .catch((err) => {
  815. log.error("failed to send resource_link to ACP", { error: err })
  816. })
  817. } else if (url.startsWith("data:")) {
  818. // Embedded content - parse data URL and send as appropriate block type
  819. const base64Match = url.match(/^data:([^;]+);base64,(.*)$/)
  820. const dataMime = base64Match?.[1]
  821. const base64Data = base64Match?.[2] ?? ""
  822. const effectiveMime = dataMime || mime
  823. if (effectiveMime.startsWith("image/")) {
  824. // Image - send as image block
  825. await this.connection
  826. .sessionUpdate({
  827. sessionId,
  828. update: {
  829. sessionUpdate: messageChunk,
  830. content: {
  831. type: "image",
  832. mimeType: effectiveMime,
  833. data: base64Data,
  834. uri: `file://${filename}`,
  835. },
  836. },
  837. })
  838. .catch((err) => {
  839. log.error("failed to send image to ACP", { error: err })
  840. })
  841. } else {
  842. // Non-image: text types get decoded, binary types stay as blob
  843. const isText = effectiveMime.startsWith("text/") || effectiveMime === "application/json"
  844. const resource = isText
  845. ? {
  846. uri: `file://${filename}`,
  847. mimeType: effectiveMime,
  848. text: Buffer.from(base64Data, "base64").toString("utf-8"),
  849. }
  850. : { uri: `file://${filename}`, mimeType: effectiveMime, blob: base64Data }
  851. await this.connection
  852. .sessionUpdate({
  853. sessionId,
  854. update: {
  855. sessionUpdate: messageChunk,
  856. content: { type: "resource", resource },
  857. },
  858. })
  859. .catch((err) => {
  860. log.error("failed to send resource to ACP", { error: err })
  861. })
  862. }
  863. }
  864. // URLs that don't match file:// or data: are skipped (unsupported)
  865. } else if (part.type === "reasoning") {
  866. if (part.text) {
  867. await this.connection
  868. .sessionUpdate({
  869. sessionId,
  870. update: {
  871. sessionUpdate: "agent_thought_chunk",
  872. content: {
  873. type: "text",
  874. text: part.text,
  875. },
  876. },
  877. })
  878. .catch((err) => {
  879. log.error("failed to send reasoning to ACP", { error: err })
  880. })
  881. }
  882. }
  883. }
  884. }
  885. private async loadSessionMode(params: LoadSessionRequest) {
  886. const directory = params.cwd
  887. const model = await defaultModel(this.config, directory)
  888. const sessionId = params.sessionId
  889. const providers = await this.sdk.config.providers({ directory }).then((x) => x.data!.providers)
  890. const entries = providers.sort((a, b) => {
  891. const nameA = a.name.toLowerCase()
  892. const nameB = b.name.toLowerCase()
  893. if (nameA < nameB) return -1
  894. if (nameA > nameB) return 1
  895. return 0
  896. })
  897. const availableModels = entries.flatMap((provider) => {
  898. const models = Provider.sort(Object.values(provider.models))
  899. return models.map((model) => ({
  900. modelId: `${provider.id}/${model.id}`,
  901. name: `${provider.name}/${model.name}`,
  902. }))
  903. })
  904. const agents = await this.config.sdk.app
  905. .agents(
  906. {
  907. directory,
  908. },
  909. { throwOnError: true },
  910. )
  911. .then((resp) => resp.data!)
  912. const commands = await this.config.sdk.command
  913. .list(
  914. {
  915. directory,
  916. },
  917. { throwOnError: true },
  918. )
  919. .then((resp) => resp.data!)
  920. const availableCommands = commands.map((command) => ({
  921. name: command.name,
  922. description: command.description ?? "",
  923. }))
  924. const names = new Set(availableCommands.map((c) => c.name))
  925. if (!names.has("compact"))
  926. availableCommands.push({
  927. name: "compact",
  928. description: "compact the session",
  929. })
  930. const availableModes = agents
  931. .filter((agent) => agent.mode !== "subagent" && !agent.hidden)
  932. .map((agent) => ({
  933. id: agent.name,
  934. name: agent.name,
  935. description: agent.description,
  936. }))
  937. const defaultAgentName = await AgentModule.defaultAgent()
  938. const currentModeId = availableModes.find((m) => m.name === defaultAgentName)?.id ?? availableModes[0].id
  939. // Persist the default mode so prompt() uses it immediately
  940. this.sessionManager.setMode(sessionId, currentModeId)
  941. const mcpServers: Record<string, Config.Mcp> = {}
  942. for (const server of params.mcpServers) {
  943. if ("type" in server) {
  944. mcpServers[server.name] = {
  945. url: server.url,
  946. headers: server.headers.reduce<Record<string, string>>((acc, { name, value }) => {
  947. acc[name] = value
  948. return acc
  949. }, {}),
  950. type: "remote",
  951. }
  952. } else {
  953. mcpServers[server.name] = {
  954. type: "local",
  955. command: [server.command, ...server.args],
  956. environment: server.env.reduce<Record<string, string>>((acc, { name, value }) => {
  957. acc[name] = value
  958. return acc
  959. }, {}),
  960. }
  961. }
  962. }
  963. await Promise.all(
  964. Object.entries(mcpServers).map(async ([key, mcp]) => {
  965. await this.sdk.mcp
  966. .add(
  967. {
  968. directory,
  969. name: key,
  970. config: mcp,
  971. },
  972. { throwOnError: true },
  973. )
  974. .catch((error) => {
  975. log.error("failed to add mcp server", { name: key, error })
  976. })
  977. }),
  978. )
  979. setTimeout(() => {
  980. this.connection.sessionUpdate({
  981. sessionId,
  982. update: {
  983. sessionUpdate: "available_commands_update",
  984. availableCommands,
  985. },
  986. })
  987. }, 0)
  988. return {
  989. sessionId,
  990. models: {
  991. currentModelId: `${model.providerID}/${model.modelID}`,
  992. availableModels,
  993. },
  994. modes: {
  995. availableModes,
  996. currentModeId,
  997. },
  998. _meta: {},
  999. }
  1000. }
  1001. async unstable_setSessionModel(params: SetSessionModelRequest) {
  1002. const session = this.sessionManager.get(params.sessionId)
  1003. const model = Provider.parseModel(params.modelId)
  1004. this.sessionManager.setModel(session.id, {
  1005. providerID: model.providerID,
  1006. modelID: model.modelID,
  1007. })
  1008. return {
  1009. _meta: {},
  1010. }
  1011. }
  1012. async setSessionMode(params: SetSessionModeRequest): Promise<SetSessionModeResponse | void> {
  1013. this.sessionManager.get(params.sessionId)
  1014. await this.config.sdk.app
  1015. .agents({}, { throwOnError: true })
  1016. .then((x) => x.data)
  1017. .then((agent) => {
  1018. if (!agent) throw new Error(`Agent not found: ${params.modeId}`)
  1019. })
  1020. this.sessionManager.setMode(params.sessionId, params.modeId)
  1021. }
  1022. async prompt(params: PromptRequest) {
  1023. const sessionID = params.sessionId
  1024. const session = this.sessionManager.get(sessionID)
  1025. const directory = session.cwd
  1026. const current = session.model
  1027. const model = current ?? (await defaultModel(this.config, directory))
  1028. if (!current) {
  1029. this.sessionManager.setModel(session.id, model)
  1030. }
  1031. const agent = session.modeId ?? (await AgentModule.defaultAgent())
  1032. const parts: Array<
  1033. | { type: "text"; text: string; synthetic?: boolean; ignored?: boolean }
  1034. | { type: "file"; url: string; filename: string; mime: string }
  1035. > = []
  1036. for (const part of params.prompt) {
  1037. switch (part.type) {
  1038. case "text":
  1039. const audience = part.annotations?.audience
  1040. const forAssistant = audience?.length === 1 && audience[0] === "assistant"
  1041. const forUser = audience?.length === 1 && audience[0] === "user"
  1042. parts.push({
  1043. type: "text" as const,
  1044. text: part.text,
  1045. ...(forAssistant && { synthetic: true }),
  1046. ...(forUser && { ignored: true }),
  1047. })
  1048. break
  1049. case "image": {
  1050. const parsed = parseUri(part.uri ?? "")
  1051. const filename = parsed.type === "file" ? parsed.filename : "image"
  1052. if (part.data) {
  1053. parts.push({
  1054. type: "file",
  1055. url: `data:${part.mimeType};base64,${part.data}`,
  1056. filename,
  1057. mime: part.mimeType,
  1058. })
  1059. } else if (part.uri && part.uri.startsWith("http:")) {
  1060. parts.push({
  1061. type: "file",
  1062. url: part.uri,
  1063. filename,
  1064. mime: part.mimeType,
  1065. })
  1066. }
  1067. break
  1068. }
  1069. case "resource_link":
  1070. const parsed = parseUri(part.uri)
  1071. // Use the name from resource_link if available
  1072. if (part.name && parsed.type === "file") {
  1073. parsed.filename = part.name
  1074. }
  1075. parts.push(parsed)
  1076. break
  1077. case "resource": {
  1078. const resource = part.resource
  1079. if ("text" in resource && resource.text) {
  1080. parts.push({
  1081. type: "text",
  1082. text: resource.text,
  1083. })
  1084. } else if ("blob" in resource && resource.blob && resource.mimeType) {
  1085. // Binary resource (PDFs, etc.): store as file part with data URL
  1086. const parsed = parseUri(resource.uri ?? "")
  1087. const filename = parsed.type === "file" ? parsed.filename : "file"
  1088. parts.push({
  1089. type: "file",
  1090. url: `data:${resource.mimeType};base64,${resource.blob}`,
  1091. filename,
  1092. mime: resource.mimeType,
  1093. })
  1094. }
  1095. break
  1096. }
  1097. default:
  1098. break
  1099. }
  1100. }
  1101. log.info("parts", { parts })
  1102. const cmd = (() => {
  1103. const text = parts
  1104. .filter((p): p is { type: "text"; text: string } => p.type === "text")
  1105. .map((p) => p.text)
  1106. .join("")
  1107. .trim()
  1108. if (!text.startsWith("/")) return
  1109. const [name, ...rest] = text.slice(1).split(/\s+/)
  1110. return { name, args: rest.join(" ").trim() }
  1111. })()
  1112. const done = {
  1113. stopReason: "end_turn" as const,
  1114. _meta: {},
  1115. }
  1116. if (!cmd) {
  1117. await this.sdk.session.prompt({
  1118. sessionID,
  1119. model: {
  1120. providerID: model.providerID,
  1121. modelID: model.modelID,
  1122. },
  1123. parts,
  1124. agent,
  1125. directory,
  1126. })
  1127. return done
  1128. }
  1129. const command = await this.config.sdk.command
  1130. .list({ directory }, { throwOnError: true })
  1131. .then((x) => x.data!.find((c) => c.name === cmd.name))
  1132. if (command) {
  1133. await this.sdk.session.command({
  1134. sessionID,
  1135. command: command.name,
  1136. arguments: cmd.args,
  1137. model: model.providerID + "/" + model.modelID,
  1138. agent,
  1139. directory,
  1140. })
  1141. return done
  1142. }
  1143. switch (cmd.name) {
  1144. case "compact":
  1145. await this.config.sdk.session.summarize(
  1146. {
  1147. sessionID,
  1148. directory,
  1149. providerID: model.providerID,
  1150. modelID: model.modelID,
  1151. },
  1152. { throwOnError: true },
  1153. )
  1154. break
  1155. }
  1156. return done
  1157. }
  1158. async cancel(params: CancelNotification) {
  1159. const session = this.sessionManager.get(params.sessionId)
  1160. await this.config.sdk.session.abort(
  1161. {
  1162. sessionID: params.sessionId,
  1163. directory: session.cwd,
  1164. },
  1165. { throwOnError: true },
  1166. )
  1167. }
  1168. }
  1169. function toToolKind(toolName: string): ToolKind {
  1170. const tool = toolName.toLocaleLowerCase()
  1171. switch (tool) {
  1172. case "bash":
  1173. return "execute"
  1174. case "webfetch":
  1175. return "fetch"
  1176. case "edit":
  1177. case "patch":
  1178. case "write":
  1179. return "edit"
  1180. case "grep":
  1181. case "glob":
  1182. case "context7_resolve_library_id":
  1183. case "context7_get_library_docs":
  1184. return "search"
  1185. case "list":
  1186. case "read":
  1187. return "read"
  1188. default:
  1189. return "other"
  1190. }
  1191. }
  1192. function toLocations(toolName: string, input: Record<string, any>): { path: string }[] {
  1193. const tool = toolName.toLocaleLowerCase()
  1194. switch (tool) {
  1195. case "read":
  1196. case "edit":
  1197. case "write":
  1198. return input["filePath"] ? [{ path: input["filePath"] }] : []
  1199. case "glob":
  1200. case "grep":
  1201. return input["path"] ? [{ path: input["path"] }] : []
  1202. case "bash":
  1203. return []
  1204. case "list":
  1205. return input["path"] ? [{ path: input["path"] }] : []
  1206. default:
  1207. return []
  1208. }
  1209. }
  1210. async function defaultModel(config: ACPConfig, cwd?: string) {
  1211. const sdk = config.sdk
  1212. const configured = config.defaultModel
  1213. if (configured) return configured
  1214. const directory = cwd ?? process.cwd()
  1215. const specified = await sdk.config
  1216. .get({ directory }, { throwOnError: true })
  1217. .then((resp) => {
  1218. const cfg = resp.data
  1219. if (!cfg || !cfg.model) return undefined
  1220. const parsed = Provider.parseModel(cfg.model)
  1221. return {
  1222. providerID: parsed.providerID,
  1223. modelID: parsed.modelID,
  1224. }
  1225. })
  1226. .catch((error) => {
  1227. log.error("failed to load user config for default model", { error })
  1228. return undefined
  1229. })
  1230. const providers = await sdk.config
  1231. .providers({ directory }, { throwOnError: true })
  1232. .then((x) => x.data?.providers ?? [])
  1233. .catch((error) => {
  1234. log.error("failed to list providers for default model", { error })
  1235. return []
  1236. })
  1237. if (specified && providers.length) {
  1238. const provider = providers.find((p) => p.id === specified.providerID)
  1239. if (provider && provider.models[specified.modelID]) return specified
  1240. }
  1241. if (specified && !providers.length) return specified
  1242. const opencodeProvider = providers.find((p) => p.id === "opencode")
  1243. if (opencodeProvider) {
  1244. if (opencodeProvider.models["big-pickle"]) {
  1245. return { providerID: "opencode", modelID: "big-pickle" }
  1246. }
  1247. const [best] = Provider.sort(Object.values(opencodeProvider.models))
  1248. if (best) {
  1249. return {
  1250. providerID: best.providerID,
  1251. modelID: best.id,
  1252. }
  1253. }
  1254. }
  1255. const models = providers.flatMap((p) => Object.values(p.models))
  1256. const [best] = Provider.sort(models)
  1257. if (best) {
  1258. return {
  1259. providerID: best.providerID,
  1260. modelID: best.id,
  1261. }
  1262. }
  1263. if (specified) return specified
  1264. return { providerID: "opencode", modelID: "big-pickle" }
  1265. }
  1266. function parseUri(
  1267. uri: string,
  1268. ): { type: "file"; url: string; filename: string; mime: string } | { type: "text"; text: string } {
  1269. try {
  1270. if (uri.startsWith("file://")) {
  1271. const path = uri.slice(7)
  1272. const name = path.split("/").pop() || path
  1273. return {
  1274. type: "file",
  1275. url: uri,
  1276. filename: name,
  1277. mime: "text/plain",
  1278. }
  1279. }
  1280. if (uri.startsWith("zed://")) {
  1281. const url = new URL(uri)
  1282. const path = url.searchParams.get("path")
  1283. if (path) {
  1284. const name = path.split("/").pop() || path
  1285. return {
  1286. type: "file",
  1287. url: `file://${path}`,
  1288. filename: name,
  1289. mime: "text/plain",
  1290. }
  1291. }
  1292. }
  1293. return {
  1294. type: "text",
  1295. text: uri,
  1296. }
  1297. } catch {
  1298. return {
  1299. type: "text",
  1300. text: uri,
  1301. }
  1302. }
  1303. }
  1304. function getNewContent(fileOriginal: string, unifiedDiff: string): string | undefined {
  1305. const result = applyPatch(fileOriginal, unifiedDiff)
  1306. if (result === false) {
  1307. log.error("Failed to apply unified diff (context mismatch)")
  1308. return undefined
  1309. }
  1310. return result
  1311. }
  1312. }