server.ts 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838
  1. import { Log } from "../util/log"
  2. import { Bus } from "../bus"
  3. import { describeRoute, generateSpecs, validator, resolver, openAPIRouteHandler } from "hono-openapi"
  4. import { Hono } from "hono"
  5. import { cors } from "hono/cors"
  6. import { stream, streamSSE } from "hono/streaming"
  7. import { proxy } from "hono/proxy"
  8. import { Session } from "../session"
  9. import z from "zod"
  10. import { Provider } from "../provider/provider"
  11. import { mapValues } from "remeda"
  12. import { NamedError } from "../util/error"
  13. import { ModelsDev } from "../provider/models"
  14. import { Ripgrep } from "../file/ripgrep"
  15. import { Config } from "../config/config"
  16. import { File } from "../file"
  17. import { LSP } from "../lsp"
  18. import { Format } from "../format"
  19. import { MessageV2 } from "../session/message-v2"
  20. import { TuiRoute } from "./tui"
  21. import { Permission } from "../permission"
  22. import { Instance } from "../project/instance"
  23. import { Agent } from "../agent/agent"
  24. import { Auth } from "../auth"
  25. import { Command } from "../command"
  26. import { Global } from "../global"
  27. import { ProjectRoute } from "./project"
  28. import { ToolRegistry } from "../tool/registry"
  29. import { zodToJsonSchema } from "zod-to-json-schema"
  30. import { SessionLock } from "../session/lock"
  31. import { SessionPrompt } from "../session/prompt"
  32. import { SessionCompaction } from "../session/compaction"
  33. import { SessionRevert } from "../session/revert"
  34. import { lazy } from "../util/lazy"
  35. import { Todo } from "../session/todo"
  36. import { InstanceBootstrap } from "../project/bootstrap"
  37. import { MCP } from "../mcp"
  38. import { Storage } from "../storage/storage"
  39. import type { ContentfulStatusCode } from "hono/utils/http-status"
  40. import { TuiEvent } from "@/cli/cmd/tui/event"
  41. import { Snapshot } from "@/snapshot"
  42. import { SessionSummary } from "@/session/summary"
  43. import { GlobalBus } from "@/bus/global"
  44. const ERRORS = {
  45. 400: {
  46. description: "Bad request",
  47. content: {
  48. "application/json": {
  49. schema: resolver(
  50. z
  51. .object({
  52. data: z.any(),
  53. errors: z.array(z.record(z.string(), z.any())),
  54. success: z.literal(false),
  55. })
  56. .meta({
  57. ref: "BadRequestError",
  58. }),
  59. ),
  60. },
  61. },
  62. },
  63. 404: {
  64. description: "Not found",
  65. content: {
  66. "application/json": {
  67. schema: resolver(Storage.NotFoundError.Schema),
  68. },
  69. },
  70. },
  71. } as const
  72. function errors(...codes: number[]) {
  73. return Object.fromEntries(codes.map((code) => [code, ERRORS[code as keyof typeof ERRORS]]))
  74. }
  75. export namespace Server {
  76. const log = Log.create({ service: "server" })
  77. export const Event = {
  78. Connected: Bus.event("server.connected", z.object({})),
  79. }
  80. const app = new Hono()
  81. export const App = lazy(() =>
  82. app
  83. .onError((err, c) => {
  84. log.error("failed", {
  85. error: err,
  86. })
  87. if (err instanceof NamedError) {
  88. let status: ContentfulStatusCode
  89. if (err instanceof Storage.NotFoundError) status = 404
  90. else if (err instanceof Provider.ModelNotFoundError) status = 400
  91. else status = 500
  92. return c.json(err.toObject(), { status })
  93. }
  94. const message = err instanceof Error && err.stack ? err.stack : err.toString()
  95. return c.json(new NamedError.Unknown({ message }).toObject(), {
  96. status: 500,
  97. })
  98. })
  99. .use(async (c, next) => {
  100. const skipLogging = c.req.path === "/log"
  101. if (!skipLogging) {
  102. log.info("request", {
  103. method: c.req.method,
  104. path: c.req.path,
  105. })
  106. }
  107. const timer = log.time("request", {
  108. method: c.req.method,
  109. path: c.req.path,
  110. })
  111. await next()
  112. if (!skipLogging) {
  113. timer.stop()
  114. }
  115. })
  116. .get(
  117. "/global/event",
  118. describeRoute({
  119. description: "Get events",
  120. operationId: "global.event",
  121. responses: {
  122. 200: {
  123. description: "Event stream",
  124. content: {
  125. "text/event-stream": {
  126. schema: resolver(
  127. z
  128. .object({
  129. directory: z.string(),
  130. payload: Bus.payloads(),
  131. })
  132. .meta({
  133. ref: "GlobalEvent",
  134. }),
  135. ),
  136. },
  137. },
  138. },
  139. },
  140. }),
  141. async (c) => {
  142. log.info("global event connected")
  143. return streamSSE(c, async (stream) => {
  144. stream.writeSSE({
  145. data: JSON.stringify({
  146. type: "server.connected",
  147. properties: {},
  148. }),
  149. })
  150. async function handler(event: any) {
  151. await stream.writeSSE({
  152. data: JSON.stringify(event),
  153. })
  154. }
  155. GlobalBus.on("event", handler)
  156. await new Promise<void>((resolve) => {
  157. stream.onAbort(() => {
  158. GlobalBus.off("event", handler)
  159. resolve()
  160. log.info("global event disconnected")
  161. })
  162. })
  163. })
  164. },
  165. )
  166. .use(async (c, next) => {
  167. const directory = c.req.query("directory") ?? process.cwd()
  168. return Instance.provide({
  169. directory,
  170. init: InstanceBootstrap,
  171. async fn() {
  172. return next()
  173. },
  174. })
  175. })
  176. .use(cors())
  177. .get(
  178. "/doc",
  179. openAPIRouteHandler(app, {
  180. documentation: {
  181. info: {
  182. title: "opencode",
  183. version: "0.0.3",
  184. description: "opencode api",
  185. },
  186. openapi: "3.1.1",
  187. },
  188. }),
  189. )
  190. .use(validator("query", z.object({ directory: z.string().optional() })))
  191. .route("/project", ProjectRoute)
  192. .get(
  193. "/config",
  194. describeRoute({
  195. description: "Get config info",
  196. operationId: "config.get",
  197. responses: {
  198. 200: {
  199. description: "Get config info",
  200. content: {
  201. "application/json": {
  202. schema: resolver(Config.Info),
  203. },
  204. },
  205. },
  206. },
  207. }),
  208. async (c) => {
  209. return c.json(await Config.get())
  210. },
  211. )
  212. .patch(
  213. "/config",
  214. describeRoute({
  215. description: "Update config",
  216. operationId: "config.update",
  217. responses: {
  218. 200: {
  219. description: "Successfully updated config",
  220. content: {
  221. "application/json": {
  222. schema: resolver(Config.Info),
  223. },
  224. },
  225. },
  226. ...errors(400),
  227. },
  228. }),
  229. validator("json", Config.Info),
  230. async (c) => {
  231. const config = c.req.valid("json")
  232. await Config.update(config)
  233. return c.json(config)
  234. },
  235. )
  236. .get(
  237. "/experimental/tool/ids",
  238. describeRoute({
  239. description: "List all tool IDs (including built-in and dynamically registered)",
  240. operationId: "tool.ids",
  241. responses: {
  242. 200: {
  243. description: "Tool IDs",
  244. content: {
  245. "application/json": {
  246. schema: resolver(z.array(z.string()).meta({ ref: "ToolIDs" })),
  247. },
  248. },
  249. },
  250. ...errors(400),
  251. },
  252. }),
  253. async (c) => {
  254. return c.json(await ToolRegistry.ids())
  255. },
  256. )
  257. .get(
  258. "/experimental/tool",
  259. describeRoute({
  260. description: "List tools with JSON schema parameters for a provider/model",
  261. operationId: "tool.list",
  262. responses: {
  263. 200: {
  264. description: "Tools",
  265. content: {
  266. "application/json": {
  267. schema: resolver(
  268. z
  269. .array(
  270. z
  271. .object({
  272. id: z.string(),
  273. description: z.string(),
  274. parameters: z.any(),
  275. })
  276. .meta({ ref: "ToolListItem" }),
  277. )
  278. .meta({ ref: "ToolList" }),
  279. ),
  280. },
  281. },
  282. },
  283. ...errors(400),
  284. },
  285. }),
  286. validator(
  287. "query",
  288. z.object({
  289. provider: z.string(),
  290. model: z.string(),
  291. }),
  292. ),
  293. async (c) => {
  294. const { provider, model } = c.req.valid("query")
  295. const tools = await ToolRegistry.tools(provider, model)
  296. return c.json(
  297. tools.map((t) => ({
  298. id: t.id,
  299. description: t.description,
  300. // Handle both Zod schemas and plain JSON schemas
  301. parameters: (t.parameters as any)?._def ? zodToJsonSchema(t.parameters as any) : t.parameters,
  302. })),
  303. )
  304. },
  305. )
  306. .get(
  307. "/path",
  308. describeRoute({
  309. description: "Get the current path",
  310. operationId: "path.get",
  311. responses: {
  312. 200: {
  313. description: "Path",
  314. content: {
  315. "application/json": {
  316. schema: resolver(
  317. z
  318. .object({
  319. state: z.string(),
  320. config: z.string(),
  321. worktree: z.string(),
  322. directory: z.string(),
  323. })
  324. .meta({
  325. ref: "Path",
  326. }),
  327. ),
  328. },
  329. },
  330. },
  331. },
  332. }),
  333. async (c) => {
  334. return c.json({
  335. state: Global.Path.state,
  336. config: Global.Path.config,
  337. worktree: Instance.worktree,
  338. directory: Instance.directory,
  339. })
  340. },
  341. )
  342. .get(
  343. "/session",
  344. describeRoute({
  345. description: "List all sessions",
  346. operationId: "session.list",
  347. responses: {
  348. 200: {
  349. description: "List of sessions",
  350. content: {
  351. "application/json": {
  352. schema: resolver(Session.Info.array()),
  353. },
  354. },
  355. },
  356. },
  357. }),
  358. async (c) => {
  359. const sessions = await Array.fromAsync(Session.list())
  360. sessions.sort((a, b) => b.time.updated - a.time.updated)
  361. return c.json(sessions)
  362. },
  363. )
  364. .get(
  365. "/session/:id",
  366. describeRoute({
  367. description: "Get session",
  368. operationId: "session.get",
  369. responses: {
  370. 200: {
  371. description: "Get session",
  372. content: {
  373. "application/json": {
  374. schema: resolver(Session.Info),
  375. },
  376. },
  377. },
  378. ...errors(400, 404),
  379. },
  380. }),
  381. validator(
  382. "param",
  383. z.object({
  384. id: Session.get.schema,
  385. }),
  386. ),
  387. async (c) => {
  388. const sessionID = c.req.valid("param").id
  389. const session = await Session.get(sessionID)
  390. return c.json(session)
  391. },
  392. )
  393. .get(
  394. "/session/:id/children",
  395. describeRoute({
  396. description: "Get a session's children",
  397. operationId: "session.children",
  398. responses: {
  399. 200: {
  400. description: "List of children",
  401. content: {
  402. "application/json": {
  403. schema: resolver(Session.Info.array()),
  404. },
  405. },
  406. },
  407. ...errors(400, 404),
  408. },
  409. }),
  410. validator(
  411. "param",
  412. z.object({
  413. id: Session.children.schema,
  414. }),
  415. ),
  416. async (c) => {
  417. const sessionID = c.req.valid("param").id
  418. const session = await Session.children(sessionID)
  419. return c.json(session)
  420. },
  421. )
  422. .get(
  423. "/session/:id/todo",
  424. describeRoute({
  425. description: "Get the todo list for a session",
  426. operationId: "session.todo",
  427. responses: {
  428. 200: {
  429. description: "Todo list",
  430. content: {
  431. "application/json": {
  432. schema: resolver(Todo.Info.array()),
  433. },
  434. },
  435. },
  436. ...errors(400, 404),
  437. },
  438. }),
  439. validator(
  440. "param",
  441. z.object({
  442. id: z.string().meta({ description: "Session ID" }),
  443. }),
  444. ),
  445. async (c) => {
  446. const sessionID = c.req.valid("param").id
  447. const todos = await Todo.get(sessionID)
  448. return c.json(todos)
  449. },
  450. )
  451. .post(
  452. "/session",
  453. describeRoute({
  454. description: "Create a new session",
  455. operationId: "session.create",
  456. responses: {
  457. ...errors(400),
  458. 200: {
  459. description: "Successfully created session",
  460. content: {
  461. "application/json": {
  462. schema: resolver(Session.Info),
  463. },
  464. },
  465. },
  466. },
  467. }),
  468. validator("json", Session.create.schema.optional()),
  469. async (c) => {
  470. const body = c.req.valid("json") ?? {}
  471. const session = await Session.create(body)
  472. return c.json(session)
  473. },
  474. )
  475. .delete(
  476. "/session/:id",
  477. describeRoute({
  478. description: "Delete a session and all its data",
  479. operationId: "session.delete",
  480. responses: {
  481. 200: {
  482. description: "Successfully deleted session",
  483. content: {
  484. "application/json": {
  485. schema: resolver(z.boolean()),
  486. },
  487. },
  488. },
  489. ...errors(400, 404),
  490. },
  491. }),
  492. validator(
  493. "param",
  494. z.object({
  495. id: Session.remove.schema,
  496. }),
  497. ),
  498. async (c) => {
  499. const sessionID = c.req.valid("param").id
  500. await Session.remove(sessionID)
  501. await Bus.publish(TuiEvent.CommandExecute, {
  502. command: "session.list",
  503. })
  504. return c.json(true)
  505. },
  506. )
  507. .patch(
  508. "/session/:id",
  509. describeRoute({
  510. description: "Update session properties",
  511. operationId: "session.update",
  512. responses: {
  513. 200: {
  514. description: "Successfully updated session",
  515. content: {
  516. "application/json": {
  517. schema: resolver(Session.Info),
  518. },
  519. },
  520. },
  521. ...errors(400, 404),
  522. },
  523. }),
  524. validator(
  525. "param",
  526. z.object({
  527. id: z.string(),
  528. }),
  529. ),
  530. validator(
  531. "json",
  532. z.object({
  533. title: z.string().optional(),
  534. }),
  535. ),
  536. async (c) => {
  537. const sessionID = c.req.valid("param").id
  538. const updates = c.req.valid("json")
  539. const updatedSession = await Session.update(sessionID, (session) => {
  540. if (updates.title !== undefined) {
  541. session.title = updates.title
  542. }
  543. })
  544. return c.json(updatedSession)
  545. },
  546. )
  547. .post(
  548. "/session/:id/init",
  549. describeRoute({
  550. description: "Analyze the app and create an AGENTS.md file",
  551. operationId: "session.init",
  552. responses: {
  553. 200: {
  554. description: "200",
  555. content: {
  556. "application/json": {
  557. schema: resolver(z.boolean()),
  558. },
  559. },
  560. },
  561. ...errors(400, 404),
  562. },
  563. }),
  564. validator(
  565. "param",
  566. z.object({
  567. id: z.string().meta({ description: "Session ID" }),
  568. }),
  569. ),
  570. validator("json", Session.initialize.schema.omit({ sessionID: true })),
  571. async (c) => {
  572. const sessionID = c.req.valid("param").id
  573. const body = c.req.valid("json")
  574. await Session.initialize({ ...body, sessionID })
  575. return c.json(true)
  576. },
  577. )
  578. .post(
  579. "/session/:id/fork",
  580. describeRoute({
  581. description: "Fork an existing session at a specific message",
  582. operationId: "session.fork",
  583. responses: {
  584. 200: {
  585. description: "200",
  586. content: {
  587. "application/json": {
  588. schema: resolver(Session.Info),
  589. },
  590. },
  591. },
  592. },
  593. }),
  594. validator(
  595. "param",
  596. z.object({
  597. id: Session.fork.schema.shape.sessionID,
  598. }),
  599. ),
  600. validator("json", Session.fork.schema.omit({ sessionID: true })),
  601. async (c) => {
  602. const sessionID = c.req.valid("param").id
  603. const body = c.req.valid("json")
  604. const result = await Session.fork({ ...body, sessionID })
  605. return c.json(result)
  606. },
  607. )
  608. .post(
  609. "/session/:id/abort",
  610. describeRoute({
  611. description: "Abort a session",
  612. operationId: "session.abort",
  613. responses: {
  614. 200: {
  615. description: "Aborted session",
  616. content: {
  617. "application/json": {
  618. schema: resolver(z.boolean()),
  619. },
  620. },
  621. },
  622. ...errors(400, 404),
  623. },
  624. }),
  625. validator(
  626. "param",
  627. z.object({
  628. id: z.string(),
  629. }),
  630. ),
  631. async (c) => {
  632. return c.json(SessionLock.abort(c.req.valid("param").id))
  633. },
  634. )
  635. .post(
  636. "/session/:id/share",
  637. describeRoute({
  638. description: "Share a session",
  639. operationId: "session.share",
  640. responses: {
  641. 200: {
  642. description: "Successfully shared session",
  643. content: {
  644. "application/json": {
  645. schema: resolver(Session.Info),
  646. },
  647. },
  648. },
  649. ...errors(400, 404),
  650. },
  651. }),
  652. validator(
  653. "param",
  654. z.object({
  655. id: z.string(),
  656. }),
  657. ),
  658. async (c) => {
  659. const id = c.req.valid("param").id
  660. await Session.share(id)
  661. const session = await Session.get(id)
  662. return c.json(session)
  663. },
  664. )
  665. .get(
  666. "/session/:id/diff",
  667. describeRoute({
  668. description: "Get the diff that resulted from this user message",
  669. operationId: "session.diff",
  670. responses: {
  671. 200: {
  672. description: "Successfully retrieved diff",
  673. content: {
  674. "application/json": {
  675. schema: resolver(Snapshot.FileDiff.array()),
  676. },
  677. },
  678. },
  679. },
  680. }),
  681. validator(
  682. "param",
  683. z.object({
  684. id: SessionSummary.diff.schema.shape.sessionID,
  685. }),
  686. ),
  687. validator(
  688. "query",
  689. z.object({
  690. messageID: SessionSummary.diff.schema.shape.messageID,
  691. }),
  692. ),
  693. async (c) => {
  694. const query = c.req.valid("query")
  695. const params = c.req.valid("param")
  696. const result = await SessionSummary.diff({
  697. sessionID: params.id,
  698. messageID: query.messageID,
  699. })
  700. return c.json(result)
  701. },
  702. )
  703. .delete(
  704. "/session/:id/share",
  705. describeRoute({
  706. description: "Unshare the session",
  707. operationId: "session.unshare",
  708. responses: {
  709. 200: {
  710. description: "Successfully unshared session",
  711. content: {
  712. "application/json": {
  713. schema: resolver(Session.Info),
  714. },
  715. },
  716. },
  717. ...errors(400, 404),
  718. },
  719. }),
  720. validator(
  721. "param",
  722. z.object({
  723. id: Session.unshare.schema,
  724. }),
  725. ),
  726. async (c) => {
  727. const id = c.req.valid("param").id
  728. await Session.unshare(id)
  729. const session = await Session.get(id)
  730. return c.json(session)
  731. },
  732. )
  733. .post(
  734. "/session/:id/summarize",
  735. describeRoute({
  736. description: "Summarize the session",
  737. operationId: "session.summarize",
  738. responses: {
  739. 200: {
  740. description: "Summarized session",
  741. content: {
  742. "application/json": {
  743. schema: resolver(z.boolean()),
  744. },
  745. },
  746. },
  747. ...errors(400, 404),
  748. },
  749. }),
  750. validator(
  751. "param",
  752. z.object({
  753. id: z.string().meta({ description: "Session ID" }),
  754. }),
  755. ),
  756. validator(
  757. "json",
  758. z.object({
  759. providerID: z.string(),
  760. modelID: z.string(),
  761. }),
  762. ),
  763. async (c) => {
  764. const id = c.req.valid("param").id
  765. const body = c.req.valid("json")
  766. await SessionCompaction.run({ ...body, sessionID: id })
  767. return c.json(true)
  768. },
  769. )
  770. .get(
  771. "/session/:id/message",
  772. describeRoute({
  773. description: "List messages for a session",
  774. operationId: "session.messages",
  775. responses: {
  776. 200: {
  777. description: "List of messages",
  778. content: {
  779. "application/json": {
  780. schema: resolver(MessageV2.WithParts.array()),
  781. },
  782. },
  783. },
  784. ...errors(400, 404),
  785. },
  786. }),
  787. validator(
  788. "param",
  789. z.object({
  790. id: z.string().meta({ description: "Session ID" }),
  791. }),
  792. ),
  793. validator(
  794. "query",
  795. z.object({
  796. limit: z.coerce.number().optional(),
  797. }),
  798. ),
  799. async (c) => {
  800. const query = c.req.valid("query")
  801. const messages = await Session.messages({
  802. sessionID: c.req.valid("param").id,
  803. limit: query.limit,
  804. })
  805. return c.json(messages)
  806. },
  807. )
  808. .get(
  809. "/session/:id/diff",
  810. describeRoute({
  811. description: "Get the diff for this session",
  812. operationId: "session.diff",
  813. responses: {
  814. 200: {
  815. description: "List of diffs",
  816. content: {
  817. "application/json": {
  818. schema: resolver(Snapshot.FileDiff.array()),
  819. },
  820. },
  821. },
  822. ...errors(400, 404),
  823. },
  824. }),
  825. validator(
  826. "param",
  827. z.object({
  828. id: z.string().meta({ description: "Session ID" }),
  829. }),
  830. ),
  831. async (c) => {
  832. const diff = await Session.diff(c.req.valid("param").id)
  833. return c.json(diff)
  834. },
  835. )
  836. .get(
  837. "/session/:id/message/:messageID",
  838. describeRoute({
  839. description: "Get a message from a session",
  840. operationId: "session.message",
  841. responses: {
  842. 200: {
  843. description: "Message",
  844. content: {
  845. "application/json": {
  846. schema: resolver(
  847. z.object({
  848. info: MessageV2.Info,
  849. parts: MessageV2.Part.array(),
  850. }),
  851. ),
  852. },
  853. },
  854. },
  855. ...errors(400, 404),
  856. },
  857. }),
  858. validator(
  859. "param",
  860. z.object({
  861. id: z.string().meta({ description: "Session ID" }),
  862. messageID: z.string().meta({ description: "Message ID" }),
  863. }),
  864. ),
  865. async (c) => {
  866. const params = c.req.valid("param")
  867. const message = await MessageV2.get({
  868. sessionID: params.id,
  869. messageID: params.messageID,
  870. })
  871. return c.json(message)
  872. },
  873. )
  874. .post(
  875. "/session/:id/message",
  876. describeRoute({
  877. description: "Create and send a new message to a session",
  878. operationId: "session.prompt",
  879. responses: {
  880. 200: {
  881. description: "Created message",
  882. content: {
  883. "application/json": {
  884. schema: resolver(
  885. z.object({
  886. info: MessageV2.Assistant,
  887. parts: MessageV2.Part.array(),
  888. }),
  889. ),
  890. },
  891. },
  892. },
  893. ...errors(400, 404),
  894. },
  895. }),
  896. validator(
  897. "param",
  898. z.object({
  899. id: z.string().meta({ description: "Session ID" }),
  900. }),
  901. ),
  902. validator("json", SessionPrompt.PromptInput.omit({ sessionID: true })),
  903. async (c) => {
  904. c.status(200)
  905. c.header("Content-Type", "application/json")
  906. return stream(c, async (stream) => {
  907. const sessionID = c.req.valid("param").id
  908. const body = c.req.valid("json")
  909. const msg = await SessionPrompt.prompt({ ...body, sessionID })
  910. stream.write(JSON.stringify(msg))
  911. })
  912. },
  913. )
  914. .post(
  915. "/session/:id/command",
  916. describeRoute({
  917. description: "Send a new command to a session",
  918. operationId: "session.command",
  919. responses: {
  920. 200: {
  921. description: "Created message",
  922. content: {
  923. "application/json": {
  924. schema: resolver(
  925. z.object({
  926. info: MessageV2.Assistant,
  927. parts: MessageV2.Part.array(),
  928. }),
  929. ),
  930. },
  931. },
  932. },
  933. ...errors(400, 404),
  934. },
  935. }),
  936. validator(
  937. "param",
  938. z.object({
  939. id: z.string().meta({ description: "Session ID" }),
  940. }),
  941. ),
  942. validator("json", SessionPrompt.CommandInput.omit({ sessionID: true })),
  943. async (c) => {
  944. const sessionID = c.req.valid("param").id
  945. const body = c.req.valid("json")
  946. const msg = await SessionPrompt.command({ ...body, sessionID })
  947. return c.json(msg)
  948. },
  949. )
  950. .post(
  951. "/session/:id/shell",
  952. describeRoute({
  953. description: "Run a shell command",
  954. operationId: "session.shell",
  955. responses: {
  956. 200: {
  957. description: "Created message",
  958. content: {
  959. "application/json": {
  960. schema: resolver(MessageV2.Assistant),
  961. },
  962. },
  963. },
  964. ...errors(400, 404),
  965. },
  966. }),
  967. validator(
  968. "param",
  969. z.object({
  970. id: z.string().meta({ description: "Session ID" }),
  971. }),
  972. ),
  973. validator("json", SessionPrompt.ShellInput.omit({ sessionID: true })),
  974. async (c) => {
  975. const sessionID = c.req.valid("param").id
  976. const body = c.req.valid("json")
  977. const msg = await SessionPrompt.shell({ ...body, sessionID })
  978. return c.json(msg)
  979. },
  980. )
  981. .post(
  982. "/session/:id/revert",
  983. describeRoute({
  984. description: "Revert a message",
  985. operationId: "session.revert",
  986. responses: {
  987. 200: {
  988. description: "Updated session",
  989. content: {
  990. "application/json": {
  991. schema: resolver(Session.Info),
  992. },
  993. },
  994. },
  995. ...errors(400, 404),
  996. },
  997. }),
  998. validator(
  999. "param",
  1000. z.object({
  1001. id: z.string(),
  1002. }),
  1003. ),
  1004. validator("json", SessionRevert.RevertInput.omit({ sessionID: true })),
  1005. async (c) => {
  1006. const id = c.req.valid("param").id
  1007. log.info("revert", c.req.valid("json"))
  1008. const session = await SessionRevert.revert({
  1009. sessionID: id,
  1010. ...c.req.valid("json"),
  1011. })
  1012. return c.json(session)
  1013. },
  1014. )
  1015. .post(
  1016. "/session/:id/unrevert",
  1017. describeRoute({
  1018. description: "Restore all reverted messages",
  1019. operationId: "session.unrevert",
  1020. responses: {
  1021. 200: {
  1022. description: "Updated session",
  1023. content: {
  1024. "application/json": {
  1025. schema: resolver(Session.Info),
  1026. },
  1027. },
  1028. },
  1029. ...errors(400, 404),
  1030. },
  1031. }),
  1032. validator(
  1033. "param",
  1034. z.object({
  1035. id: z.string(),
  1036. }),
  1037. ),
  1038. async (c) => {
  1039. const id = c.req.valid("param").id
  1040. const session = await SessionRevert.unrevert({ sessionID: id })
  1041. return c.json(session)
  1042. },
  1043. )
  1044. .post(
  1045. "/session/:id/permissions/:permissionID",
  1046. describeRoute({
  1047. description: "Respond to a permission request",
  1048. responses: {
  1049. 200: {
  1050. description: "Permission processed successfully",
  1051. content: {
  1052. "application/json": {
  1053. schema: resolver(z.boolean()),
  1054. },
  1055. },
  1056. },
  1057. ...errors(400, 404),
  1058. },
  1059. }),
  1060. validator(
  1061. "param",
  1062. z.object({
  1063. id: z.string(),
  1064. permissionID: z.string(),
  1065. }),
  1066. ),
  1067. validator("json", z.object({ response: Permission.Response })),
  1068. async (c) => {
  1069. const params = c.req.valid("param")
  1070. const id = params.id
  1071. const permissionID = params.permissionID
  1072. Permission.respond({
  1073. sessionID: id,
  1074. permissionID,
  1075. response: c.req.valid("json").response,
  1076. })
  1077. return c.json(true)
  1078. },
  1079. )
  1080. .get(
  1081. "/command",
  1082. describeRoute({
  1083. description: "List all commands",
  1084. operationId: "command.list",
  1085. responses: {
  1086. 200: {
  1087. description: "List of commands",
  1088. content: {
  1089. "application/json": {
  1090. schema: resolver(Command.Info.array()),
  1091. },
  1092. },
  1093. },
  1094. },
  1095. }),
  1096. async (c) => {
  1097. const commands = await Command.list()
  1098. return c.json(commands)
  1099. },
  1100. )
  1101. .get(
  1102. "/config/providers",
  1103. describeRoute({
  1104. description: "List all providers",
  1105. operationId: "config.providers",
  1106. responses: {
  1107. 200: {
  1108. description: "List of providers",
  1109. content: {
  1110. "application/json": {
  1111. schema: resolver(
  1112. z.object({
  1113. providers: ModelsDev.Provider.array(),
  1114. default: z.record(z.string(), z.string()),
  1115. }),
  1116. ),
  1117. },
  1118. },
  1119. },
  1120. },
  1121. }),
  1122. async (c) => {
  1123. using _ = log.time("providers")
  1124. const providers = await Provider.list().then((x) => mapValues(x, (item) => item.info))
  1125. return c.json({
  1126. providers: Object.values(providers),
  1127. default: mapValues(providers, (item) => Provider.sort(Object.values(item.models))[0].id),
  1128. })
  1129. },
  1130. )
  1131. .get(
  1132. "/find",
  1133. describeRoute({
  1134. description: "Find text in files",
  1135. operationId: "find.text",
  1136. responses: {
  1137. 200: {
  1138. description: "Matches",
  1139. content: {
  1140. "application/json": {
  1141. schema: resolver(Ripgrep.Match.shape.data.array()),
  1142. },
  1143. },
  1144. },
  1145. },
  1146. }),
  1147. validator(
  1148. "query",
  1149. z.object({
  1150. pattern: z.string(),
  1151. }),
  1152. ),
  1153. async (c) => {
  1154. const pattern = c.req.valid("query").pattern
  1155. const result = await Ripgrep.search({
  1156. cwd: Instance.directory,
  1157. pattern,
  1158. limit: 10,
  1159. })
  1160. return c.json(result)
  1161. },
  1162. )
  1163. .get(
  1164. "/find/file",
  1165. describeRoute({
  1166. description: "Find files",
  1167. operationId: "find.files",
  1168. responses: {
  1169. 200: {
  1170. description: "File paths",
  1171. content: {
  1172. "application/json": {
  1173. schema: resolver(z.string().array()),
  1174. },
  1175. },
  1176. },
  1177. },
  1178. }),
  1179. validator(
  1180. "query",
  1181. z.object({
  1182. query: z.string(),
  1183. dirs: z.enum(["true", "false"]).optional(),
  1184. }),
  1185. ),
  1186. async (c) => {
  1187. const query = c.req.valid("query").query
  1188. const dirs = c.req.valid("query").dirs
  1189. const results = await File.search({
  1190. query,
  1191. limit: 10,
  1192. dirs: dirs !== "false",
  1193. })
  1194. return c.json(results)
  1195. },
  1196. )
  1197. .get(
  1198. "/find/symbol",
  1199. describeRoute({
  1200. description: "Find workspace symbols",
  1201. operationId: "find.symbols",
  1202. responses: {
  1203. 200: {
  1204. description: "Symbols",
  1205. content: {
  1206. "application/json": {
  1207. schema: resolver(LSP.Symbol.array()),
  1208. },
  1209. },
  1210. },
  1211. },
  1212. }),
  1213. validator(
  1214. "query",
  1215. z.object({
  1216. query: z.string(),
  1217. }),
  1218. ),
  1219. async (c) => {
  1220. /*
  1221. const query = c.req.valid("query").query
  1222. const result = await LSP.workspaceSymbol(query)
  1223. return c.json(result)
  1224. */
  1225. return c.json([])
  1226. },
  1227. )
  1228. .get(
  1229. "/file",
  1230. describeRoute({
  1231. description: "List files and directories",
  1232. operationId: "file.list",
  1233. responses: {
  1234. 200: {
  1235. description: "Files and directories",
  1236. content: {
  1237. "application/json": {
  1238. schema: resolver(File.Node.array()),
  1239. },
  1240. },
  1241. },
  1242. },
  1243. }),
  1244. validator(
  1245. "query",
  1246. z.object({
  1247. path: z.string(),
  1248. }),
  1249. ),
  1250. async (c) => {
  1251. const path = c.req.valid("query").path
  1252. const content = await File.list(path)
  1253. return c.json(content)
  1254. },
  1255. )
  1256. .get(
  1257. "/file/content",
  1258. describeRoute({
  1259. description: "Read a file",
  1260. operationId: "file.read",
  1261. responses: {
  1262. 200: {
  1263. description: "File content",
  1264. content: {
  1265. "application/json": {
  1266. schema: resolver(File.Content),
  1267. },
  1268. },
  1269. },
  1270. },
  1271. }),
  1272. validator(
  1273. "query",
  1274. z.object({
  1275. path: z.string(),
  1276. }),
  1277. ),
  1278. async (c) => {
  1279. const path = c.req.valid("query").path
  1280. const content = await File.read(path)
  1281. return c.json(content)
  1282. },
  1283. )
  1284. .get(
  1285. "/file/status",
  1286. describeRoute({
  1287. description: "Get file status",
  1288. operationId: "file.status",
  1289. responses: {
  1290. 200: {
  1291. description: "File status",
  1292. content: {
  1293. "application/json": {
  1294. schema: resolver(File.Info.array()),
  1295. },
  1296. },
  1297. },
  1298. },
  1299. }),
  1300. async (c) => {
  1301. const content = await File.status()
  1302. return c.json(content)
  1303. },
  1304. )
  1305. .post(
  1306. "/log",
  1307. describeRoute({
  1308. description: "Write a log entry to the server logs",
  1309. operationId: "app.log",
  1310. responses: {
  1311. 200: {
  1312. description: "Log entry written successfully",
  1313. content: {
  1314. "application/json": {
  1315. schema: resolver(z.boolean()),
  1316. },
  1317. },
  1318. },
  1319. ...errors(400),
  1320. },
  1321. }),
  1322. validator(
  1323. "json",
  1324. z.object({
  1325. service: z.string().meta({ description: "Service name for the log entry" }),
  1326. level: z.enum(["debug", "info", "error", "warn"]).meta({ description: "Log level" }),
  1327. message: z.string().meta({ description: "Log message" }),
  1328. extra: z
  1329. .record(z.string(), z.any())
  1330. .optional()
  1331. .meta({ description: "Additional metadata for the log entry" }),
  1332. }),
  1333. ),
  1334. async (c) => {
  1335. const { service, level, message, extra } = c.req.valid("json")
  1336. const logger = Log.create({ service })
  1337. switch (level) {
  1338. case "debug":
  1339. logger.debug(message, extra)
  1340. break
  1341. case "info":
  1342. logger.info(message, extra)
  1343. break
  1344. case "error":
  1345. logger.error(message, extra)
  1346. break
  1347. case "warn":
  1348. logger.warn(message, extra)
  1349. break
  1350. }
  1351. return c.json(true)
  1352. },
  1353. )
  1354. .get(
  1355. "/agent",
  1356. describeRoute({
  1357. description: "List all agents",
  1358. operationId: "app.agents",
  1359. responses: {
  1360. 200: {
  1361. description: "List of agents",
  1362. content: {
  1363. "application/json": {
  1364. schema: resolver(Agent.Info.array()),
  1365. },
  1366. },
  1367. },
  1368. },
  1369. }),
  1370. async (c) => {
  1371. const modes = await Agent.list()
  1372. return c.json(modes)
  1373. },
  1374. )
  1375. .get(
  1376. "/mcp",
  1377. describeRoute({
  1378. description: "Get MCP server status",
  1379. operationId: "mcp.status",
  1380. responses: {
  1381. 200: {
  1382. description: "MCP server status",
  1383. content: {
  1384. "application/json": {
  1385. schema: resolver(z.record(z.string(), MCP.Status)),
  1386. },
  1387. },
  1388. },
  1389. },
  1390. }),
  1391. async (c) => {
  1392. return c.json(await MCP.status())
  1393. },
  1394. )
  1395. .post(
  1396. "/mcp",
  1397. describeRoute({
  1398. description: "Add MCP server dynamically",
  1399. operationId: "mcp.add",
  1400. responses: {
  1401. 200: {
  1402. description: "MCP server added successfully",
  1403. content: {
  1404. "application/json": {
  1405. schema: resolver(z.record(z.string(), MCP.Status)),
  1406. },
  1407. },
  1408. },
  1409. ...errors(400),
  1410. },
  1411. }),
  1412. validator(
  1413. "json",
  1414. z.object({
  1415. name: z.string(),
  1416. config: Config.Mcp,
  1417. }),
  1418. ),
  1419. async (c) => {
  1420. const { name, config } = c.req.valid("json")
  1421. const result = await MCP.add(name, config)
  1422. return c.json(result.status)
  1423. },
  1424. )
  1425. .get(
  1426. "/lsp",
  1427. describeRoute({
  1428. description: "Get LSP server status",
  1429. operationId: "lsp.status",
  1430. responses: {
  1431. 200: {
  1432. description: "LSP server status",
  1433. content: {
  1434. "application/json": {
  1435. schema: resolver(LSP.Status.array()),
  1436. },
  1437. },
  1438. },
  1439. },
  1440. }),
  1441. async (c) => {
  1442. return c.json(await LSP.status())
  1443. },
  1444. )
  1445. .get(
  1446. "/formatter",
  1447. describeRoute({
  1448. description: "Get formatter status",
  1449. operationId: "formatter.status",
  1450. responses: {
  1451. 200: {
  1452. description: "Formatter status",
  1453. content: {
  1454. "application/json": {
  1455. schema: resolver(Format.Status.array()),
  1456. },
  1457. },
  1458. },
  1459. },
  1460. }),
  1461. async (c) => {
  1462. return c.json(await Format.status())
  1463. },
  1464. )
  1465. .post(
  1466. "/tui/append-prompt",
  1467. describeRoute({
  1468. description: "Append prompt to the TUI",
  1469. operationId: "tui.appendPrompt",
  1470. responses: {
  1471. 200: {
  1472. description: "Prompt processed successfully",
  1473. content: {
  1474. "application/json": {
  1475. schema: resolver(z.boolean()),
  1476. },
  1477. },
  1478. },
  1479. ...errors(400),
  1480. },
  1481. }),
  1482. validator("json", TuiEvent.PromptAppend.properties),
  1483. async (c) => {
  1484. await Bus.publish(TuiEvent.PromptAppend, c.req.valid("json"))
  1485. return c.json(true)
  1486. },
  1487. )
  1488. .post(
  1489. "/tui/open-help",
  1490. describeRoute({
  1491. description: "Open the help dialog",
  1492. operationId: "tui.openHelp",
  1493. responses: {
  1494. 200: {
  1495. description: "Help dialog opened successfully",
  1496. content: {
  1497. "application/json": {
  1498. schema: resolver(z.boolean()),
  1499. },
  1500. },
  1501. },
  1502. },
  1503. }),
  1504. async (c) => {
  1505. // TODO: open dialog
  1506. return c.json(true)
  1507. },
  1508. )
  1509. .post(
  1510. "/tui/open-sessions",
  1511. describeRoute({
  1512. description: "Open the session dialog",
  1513. operationId: "tui.openSessions",
  1514. responses: {
  1515. 200: {
  1516. description: "Session dialog opened successfully",
  1517. content: {
  1518. "application/json": {
  1519. schema: resolver(z.boolean()),
  1520. },
  1521. },
  1522. },
  1523. },
  1524. }),
  1525. async (c) => {
  1526. await Bus.publish(TuiEvent.CommandExecute, {
  1527. command: "session.list",
  1528. })
  1529. return c.json(true)
  1530. },
  1531. )
  1532. .post(
  1533. "/tui/open-themes",
  1534. describeRoute({
  1535. description: "Open the theme dialog",
  1536. operationId: "tui.openThemes",
  1537. responses: {
  1538. 200: {
  1539. description: "Theme dialog opened successfully",
  1540. content: {
  1541. "application/json": {
  1542. schema: resolver(z.boolean()),
  1543. },
  1544. },
  1545. },
  1546. },
  1547. }),
  1548. async (c) => {
  1549. await Bus.publish(TuiEvent.CommandExecute, {
  1550. command: "session.list",
  1551. })
  1552. return c.json(true)
  1553. },
  1554. )
  1555. .post(
  1556. "/tui/open-models",
  1557. describeRoute({
  1558. description: "Open the model dialog",
  1559. operationId: "tui.openModels",
  1560. responses: {
  1561. 200: {
  1562. description: "Model dialog opened successfully",
  1563. content: {
  1564. "application/json": {
  1565. schema: resolver(z.boolean()),
  1566. },
  1567. },
  1568. },
  1569. },
  1570. }),
  1571. async (c) => {
  1572. await Bus.publish(TuiEvent.CommandExecute, {
  1573. command: "model.list",
  1574. })
  1575. return c.json(true)
  1576. },
  1577. )
  1578. .post(
  1579. "/tui/submit-prompt",
  1580. describeRoute({
  1581. description: "Submit the prompt",
  1582. operationId: "tui.submitPrompt",
  1583. responses: {
  1584. 200: {
  1585. description: "Prompt submitted successfully",
  1586. content: {
  1587. "application/json": {
  1588. schema: resolver(z.boolean()),
  1589. },
  1590. },
  1591. },
  1592. },
  1593. }),
  1594. async (c) => {
  1595. await Bus.publish(TuiEvent.CommandExecute, {
  1596. command: "prompt.submit",
  1597. })
  1598. return c.json(true)
  1599. },
  1600. )
  1601. .post(
  1602. "/tui/clear-prompt",
  1603. describeRoute({
  1604. description: "Clear the prompt",
  1605. operationId: "tui.clearPrompt",
  1606. responses: {
  1607. 200: {
  1608. description: "Prompt cleared successfully",
  1609. content: {
  1610. "application/json": {
  1611. schema: resolver(z.boolean()),
  1612. },
  1613. },
  1614. },
  1615. },
  1616. }),
  1617. async (c) => {
  1618. await Bus.publish(TuiEvent.CommandExecute, {
  1619. command: "prompt.clear",
  1620. })
  1621. return c.json(true)
  1622. },
  1623. )
  1624. .post(
  1625. "/tui/execute-command",
  1626. describeRoute({
  1627. description: "Execute a TUI command (e.g. agent_cycle)",
  1628. operationId: "tui.executeCommand",
  1629. responses: {
  1630. 200: {
  1631. description: "Command executed successfully",
  1632. content: {
  1633. "application/json": {
  1634. schema: resolver(z.boolean()),
  1635. },
  1636. },
  1637. },
  1638. ...errors(400),
  1639. },
  1640. }),
  1641. validator("json", z.object({ command: z.string() })),
  1642. async (c) => {
  1643. const command = c.req.valid("json").command
  1644. await Bus.publish(TuiEvent.CommandExecute, {
  1645. // @ts-expect-error
  1646. command: {
  1647. session_new: "session.new",
  1648. session_share: "session.share",
  1649. session_interrupt: "session.interrupt",
  1650. session_compact: "session.compact",
  1651. messages_page_up: "session.page.up",
  1652. messages_page_down: "session.page.down",
  1653. messages_half_page_up: "session.half.page.up",
  1654. messages_half_page_down: "session.half.page.down",
  1655. messages_first: "session.first",
  1656. messages_last: "session.last",
  1657. agent_cycle: "agent.cycle",
  1658. }[command],
  1659. })
  1660. return c.json(true)
  1661. },
  1662. )
  1663. .post(
  1664. "/tui/show-toast",
  1665. describeRoute({
  1666. description: "Show a toast notification in the TUI",
  1667. operationId: "tui.showToast",
  1668. responses: {
  1669. 200: {
  1670. description: "Toast notification shown successfully",
  1671. content: {
  1672. "application/json": {
  1673. schema: resolver(z.boolean()),
  1674. },
  1675. },
  1676. },
  1677. },
  1678. }),
  1679. validator("json", TuiEvent.ToastShow.properties),
  1680. async (c) => {
  1681. await Bus.publish(TuiEvent.ToastShow, c.req.valid("json"))
  1682. return c.json(true)
  1683. },
  1684. )
  1685. .post(
  1686. "/tui/publish",
  1687. describeRoute({
  1688. description: "Publish a TUI event",
  1689. operationId: "tui.publish",
  1690. responses: {
  1691. 200: {
  1692. description: "Event published successfully",
  1693. content: {
  1694. "application/json": {
  1695. schema: resolver(z.boolean()),
  1696. },
  1697. },
  1698. },
  1699. ...errors(400),
  1700. },
  1701. }),
  1702. validator(
  1703. "json",
  1704. z.union(
  1705. Object.values(TuiEvent).map((def) => {
  1706. return z
  1707. .object({
  1708. type: z.literal(def.type),
  1709. properties: def.properties,
  1710. })
  1711. .meta({
  1712. ref: "Event" + "." + def.type,
  1713. })
  1714. }),
  1715. ),
  1716. ),
  1717. async (c) => {
  1718. const evt = c.req.valid("json")
  1719. await Bus.publish(Object.values(TuiEvent).find((def) => def.type === evt.type)!, evt.properties)
  1720. return c.json(true)
  1721. },
  1722. )
  1723. .route("/tui/control", TuiRoute)
  1724. .put(
  1725. "/auth/:id",
  1726. describeRoute({
  1727. description: "Set authentication credentials",
  1728. operationId: "auth.set",
  1729. responses: {
  1730. 200: {
  1731. description: "Successfully set authentication credentials",
  1732. content: {
  1733. "application/json": {
  1734. schema: resolver(z.boolean()),
  1735. },
  1736. },
  1737. },
  1738. ...errors(400),
  1739. },
  1740. }),
  1741. validator(
  1742. "param",
  1743. z.object({
  1744. id: z.string(),
  1745. }),
  1746. ),
  1747. validator("json", Auth.Info),
  1748. async (c) => {
  1749. const id = c.req.valid("param").id
  1750. const info = c.req.valid("json")
  1751. await Auth.set(id, info)
  1752. return c.json(true)
  1753. },
  1754. )
  1755. .get(
  1756. "/event",
  1757. describeRoute({
  1758. description: "Get events",
  1759. operationId: "event.subscribe",
  1760. responses: {
  1761. 200: {
  1762. description: "Event stream",
  1763. content: {
  1764. "text/event-stream": {
  1765. schema: resolver(Bus.payloads()),
  1766. },
  1767. },
  1768. },
  1769. },
  1770. }),
  1771. async (c) => {
  1772. log.info("event connected")
  1773. return streamSSE(c, async (stream) => {
  1774. stream.writeSSE({
  1775. data: JSON.stringify({
  1776. type: "server.connected",
  1777. properties: {},
  1778. }),
  1779. })
  1780. const unsub = Bus.subscribeAll(async (event) => {
  1781. await stream.writeSSE({
  1782. data: JSON.stringify(event),
  1783. })
  1784. })
  1785. await new Promise<void>((resolve) => {
  1786. stream.onAbort(() => {
  1787. unsub()
  1788. resolve()
  1789. log.info("event disconnected")
  1790. })
  1791. })
  1792. })
  1793. },
  1794. )
  1795. .all("/*", async (c) => {
  1796. return proxy(`https://desktop.dev.opencode.ai${c.req.path}`, {
  1797. ...c.req,
  1798. headers: {
  1799. host: "desktop.dev.opencode.ai",
  1800. },
  1801. })
  1802. }),
  1803. )
  1804. export async function openapi() {
  1805. const result = await generateSpecs(App(), {
  1806. documentation: {
  1807. info: {
  1808. title: "opencode",
  1809. version: "1.0.0",
  1810. description: "opencode api",
  1811. },
  1812. openapi: "3.1.1",
  1813. },
  1814. })
  1815. return result
  1816. }
  1817. export function listen(opts: { port: number; hostname: string }) {
  1818. const server = Bun.serve({
  1819. port: opts.port,
  1820. hostname: opts.hostname,
  1821. idleTimeout: 0,
  1822. fetch: App().fetch,
  1823. })
  1824. return server
  1825. }
  1826. }