agent.ts 42 KB

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