server.ts 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868
  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 { SessionPrompt } from "../session/prompt"
  31. import { SessionCompaction } from "../session/compaction"
  32. import { SessionRevert } from "../session/revert"
  33. import { lazy } from "../util/lazy"
  34. import { Todo } from "../session/todo"
  35. import { InstanceBootstrap } from "../project/bootstrap"
  36. import { MCP } from "../mcp"
  37. import { Storage } from "../storage/storage"
  38. import type { ContentfulStatusCode } from "hono/utils/http-status"
  39. import { TuiEvent } from "@/cli/cmd/tui/event"
  40. import { Snapshot } from "@/snapshot"
  41. import { SessionSummary } from "@/session/summary"
  42. import { GlobalBus } from "@/bus/global"
  43. import { SessionStatus } from "@/session/status"
  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/status",
  366. describeRoute({
  367. description: "Get session status",
  368. operationId: "session.status",
  369. responses: {
  370. 200: {
  371. description: "Get session status",
  372. content: {
  373. "application/json": {
  374. schema: resolver(z.record(z.string(), SessionStatus.Info)),
  375. },
  376. },
  377. },
  378. ...errors(400),
  379. },
  380. }),
  381. async (c) => {
  382. const result = SessionStatus.list()
  383. return c.json(result)
  384. },
  385. )
  386. .get(
  387. "/session/:id",
  388. describeRoute({
  389. description: "Get session",
  390. operationId: "session.get",
  391. responses: {
  392. 200: {
  393. description: "Get session",
  394. content: {
  395. "application/json": {
  396. schema: resolver(Session.Info),
  397. },
  398. },
  399. },
  400. ...errors(400, 404),
  401. },
  402. }),
  403. validator(
  404. "param",
  405. z.object({
  406. id: Session.get.schema,
  407. }),
  408. ),
  409. async (c) => {
  410. const sessionID = c.req.valid("param").id
  411. const session = await Session.get(sessionID)
  412. return c.json(session)
  413. },
  414. )
  415. .get(
  416. "/session/:id/children",
  417. describeRoute({
  418. description: "Get a session's children",
  419. operationId: "session.children",
  420. responses: {
  421. 200: {
  422. description: "List of children",
  423. content: {
  424. "application/json": {
  425. schema: resolver(Session.Info.array()),
  426. },
  427. },
  428. },
  429. ...errors(400, 404),
  430. },
  431. }),
  432. validator(
  433. "param",
  434. z.object({
  435. id: Session.children.schema,
  436. }),
  437. ),
  438. async (c) => {
  439. const sessionID = c.req.valid("param").id
  440. const session = await Session.children(sessionID)
  441. return c.json(session)
  442. },
  443. )
  444. .get(
  445. "/session/:id/todo",
  446. describeRoute({
  447. description: "Get the todo list for a session",
  448. operationId: "session.todo",
  449. responses: {
  450. 200: {
  451. description: "Todo list",
  452. content: {
  453. "application/json": {
  454. schema: resolver(Todo.Info.array()),
  455. },
  456. },
  457. },
  458. ...errors(400, 404),
  459. },
  460. }),
  461. validator(
  462. "param",
  463. z.object({
  464. id: z.string().meta({ description: "Session ID" }),
  465. }),
  466. ),
  467. async (c) => {
  468. const sessionID = c.req.valid("param").id
  469. const todos = await Todo.get(sessionID)
  470. return c.json(todos)
  471. },
  472. )
  473. .post(
  474. "/session",
  475. describeRoute({
  476. description: "Create a new session",
  477. operationId: "session.create",
  478. responses: {
  479. ...errors(400),
  480. 200: {
  481. description: "Successfully created session",
  482. content: {
  483. "application/json": {
  484. schema: resolver(Session.Info),
  485. },
  486. },
  487. },
  488. },
  489. }),
  490. validator("json", Session.create.schema.optional()),
  491. async (c) => {
  492. const body = c.req.valid("json") ?? {}
  493. const session = await Session.create(body)
  494. return c.json(session)
  495. },
  496. )
  497. .delete(
  498. "/session/:id",
  499. describeRoute({
  500. description: "Delete a session and all its data",
  501. operationId: "session.delete",
  502. responses: {
  503. 200: {
  504. description: "Successfully deleted session",
  505. content: {
  506. "application/json": {
  507. schema: resolver(z.boolean()),
  508. },
  509. },
  510. },
  511. ...errors(400, 404),
  512. },
  513. }),
  514. validator(
  515. "param",
  516. z.object({
  517. id: Session.remove.schema,
  518. }),
  519. ),
  520. async (c) => {
  521. const sessionID = c.req.valid("param").id
  522. await Session.remove(sessionID)
  523. await Bus.publish(TuiEvent.CommandExecute, {
  524. command: "session.list",
  525. })
  526. return c.json(true)
  527. },
  528. )
  529. .patch(
  530. "/session/:id",
  531. describeRoute({
  532. description: "Update session properties",
  533. operationId: "session.update",
  534. responses: {
  535. 200: {
  536. description: "Successfully updated session",
  537. content: {
  538. "application/json": {
  539. schema: resolver(Session.Info),
  540. },
  541. },
  542. },
  543. ...errors(400, 404),
  544. },
  545. }),
  546. validator(
  547. "param",
  548. z.object({
  549. id: z.string(),
  550. }),
  551. ),
  552. validator(
  553. "json",
  554. z.object({
  555. title: z.string().optional(),
  556. }),
  557. ),
  558. async (c) => {
  559. const sessionID = c.req.valid("param").id
  560. const updates = c.req.valid("json")
  561. const updatedSession = await Session.update(sessionID, (session) => {
  562. if (updates.title !== undefined) {
  563. session.title = updates.title
  564. }
  565. })
  566. return c.json(updatedSession)
  567. },
  568. )
  569. .post(
  570. "/session/:id/init",
  571. describeRoute({
  572. description: "Analyze the app and create an AGENTS.md file",
  573. operationId: "session.init",
  574. responses: {
  575. 200: {
  576. description: "200",
  577. content: {
  578. "application/json": {
  579. schema: resolver(z.boolean()),
  580. },
  581. },
  582. },
  583. ...errors(400, 404),
  584. },
  585. }),
  586. validator(
  587. "param",
  588. z.object({
  589. id: z.string().meta({ description: "Session ID" }),
  590. }),
  591. ),
  592. validator("json", Session.initialize.schema.omit({ sessionID: true })),
  593. async (c) => {
  594. const sessionID = c.req.valid("param").id
  595. const body = c.req.valid("json")
  596. await Session.initialize({ ...body, sessionID })
  597. return c.json(true)
  598. },
  599. )
  600. .post(
  601. "/session/:id/fork",
  602. describeRoute({
  603. description: "Fork an existing session at a specific message",
  604. operationId: "session.fork",
  605. responses: {
  606. 200: {
  607. description: "200",
  608. content: {
  609. "application/json": {
  610. schema: resolver(Session.Info),
  611. },
  612. },
  613. },
  614. },
  615. }),
  616. validator(
  617. "param",
  618. z.object({
  619. id: Session.fork.schema.shape.sessionID,
  620. }),
  621. ),
  622. validator("json", Session.fork.schema.omit({ sessionID: true })),
  623. async (c) => {
  624. const sessionID = c.req.valid("param").id
  625. const body = c.req.valid("json")
  626. const result = await Session.fork({ ...body, sessionID })
  627. return c.json(result)
  628. },
  629. )
  630. .post(
  631. "/session/:id/abort",
  632. describeRoute({
  633. description: "Abort a session",
  634. operationId: "session.abort",
  635. responses: {
  636. 200: {
  637. description: "Aborted session",
  638. content: {
  639. "application/json": {
  640. schema: resolver(z.boolean()),
  641. },
  642. },
  643. },
  644. ...errors(400, 404),
  645. },
  646. }),
  647. validator(
  648. "param",
  649. z.object({
  650. id: z.string(),
  651. }),
  652. ),
  653. async (c) => {
  654. SessionPrompt.cancel(c.req.valid("param").id)
  655. return c.json(true)
  656. },
  657. )
  658. .post(
  659. "/session/:id/share",
  660. describeRoute({
  661. description: "Share a session",
  662. operationId: "session.share",
  663. responses: {
  664. 200: {
  665. description: "Successfully shared session",
  666. content: {
  667. "application/json": {
  668. schema: resolver(Session.Info),
  669. },
  670. },
  671. },
  672. ...errors(400, 404),
  673. },
  674. }),
  675. validator(
  676. "param",
  677. z.object({
  678. id: z.string(),
  679. }),
  680. ),
  681. async (c) => {
  682. const id = c.req.valid("param").id
  683. await Session.share(id)
  684. const session = await Session.get(id)
  685. return c.json(session)
  686. },
  687. )
  688. .get(
  689. "/session/:id/diff",
  690. describeRoute({
  691. description: "Get the diff that resulted from this user message",
  692. operationId: "session.diff",
  693. responses: {
  694. 200: {
  695. description: "Successfully retrieved diff",
  696. content: {
  697. "application/json": {
  698. schema: resolver(Snapshot.FileDiff.array()),
  699. },
  700. },
  701. },
  702. },
  703. }),
  704. validator(
  705. "param",
  706. z.object({
  707. id: SessionSummary.diff.schema.shape.sessionID,
  708. }),
  709. ),
  710. validator(
  711. "query",
  712. z.object({
  713. messageID: SessionSummary.diff.schema.shape.messageID,
  714. }),
  715. ),
  716. async (c) => {
  717. const query = c.req.valid("query")
  718. const params = c.req.valid("param")
  719. const result = await SessionSummary.diff({
  720. sessionID: params.id,
  721. messageID: query.messageID,
  722. })
  723. return c.json(result)
  724. },
  725. )
  726. .delete(
  727. "/session/:id/share",
  728. describeRoute({
  729. description: "Unshare the session",
  730. operationId: "session.unshare",
  731. responses: {
  732. 200: {
  733. description: "Successfully unshared session",
  734. content: {
  735. "application/json": {
  736. schema: resolver(Session.Info),
  737. },
  738. },
  739. },
  740. ...errors(400, 404),
  741. },
  742. }),
  743. validator(
  744. "param",
  745. z.object({
  746. id: Session.unshare.schema,
  747. }),
  748. ),
  749. async (c) => {
  750. const id = c.req.valid("param").id
  751. await Session.unshare(id)
  752. const session = await Session.get(id)
  753. return c.json(session)
  754. },
  755. )
  756. .post(
  757. "/session/:id/summarize",
  758. describeRoute({
  759. description: "Summarize the session",
  760. operationId: "session.summarize",
  761. responses: {
  762. 200: {
  763. description: "Summarized session",
  764. content: {
  765. "application/json": {
  766. schema: resolver(z.boolean()),
  767. },
  768. },
  769. },
  770. ...errors(400, 404),
  771. },
  772. }),
  773. validator(
  774. "param",
  775. z.object({
  776. id: z.string().meta({ description: "Session ID" }),
  777. }),
  778. ),
  779. validator(
  780. "json",
  781. z.object({
  782. providerID: z.string(),
  783. modelID: z.string(),
  784. }),
  785. ),
  786. async (c) => {
  787. const id = c.req.valid("param").id
  788. const body = c.req.valid("json")
  789. await SessionCompaction.create({
  790. sessionID: id,
  791. model: {
  792. providerID: body.providerID,
  793. modelID: body.modelID,
  794. },
  795. })
  796. await SessionPrompt.loop(id)
  797. return c.json(true)
  798. },
  799. )
  800. .get(
  801. "/session/:id/message",
  802. describeRoute({
  803. description: "List messages for a session",
  804. operationId: "session.messages",
  805. responses: {
  806. 200: {
  807. description: "List of messages",
  808. content: {
  809. "application/json": {
  810. schema: resolver(MessageV2.WithParts.array()),
  811. },
  812. },
  813. },
  814. ...errors(400, 404),
  815. },
  816. }),
  817. validator(
  818. "param",
  819. z.object({
  820. id: z.string().meta({ description: "Session ID" }),
  821. }),
  822. ),
  823. validator(
  824. "query",
  825. z.object({
  826. limit: z.coerce.number().optional(),
  827. }),
  828. ),
  829. async (c) => {
  830. const query = c.req.valid("query")
  831. const messages = await Session.messages({
  832. sessionID: c.req.valid("param").id,
  833. limit: query.limit,
  834. })
  835. return c.json(messages)
  836. },
  837. )
  838. .get(
  839. "/session/:id/diff",
  840. describeRoute({
  841. description: "Get the diff for this session",
  842. operationId: "session.diff",
  843. responses: {
  844. 200: {
  845. description: "List of diffs",
  846. content: {
  847. "application/json": {
  848. schema: resolver(Snapshot.FileDiff.array()),
  849. },
  850. },
  851. },
  852. ...errors(400, 404),
  853. },
  854. }),
  855. validator(
  856. "param",
  857. z.object({
  858. id: z.string().meta({ description: "Session ID" }),
  859. }),
  860. ),
  861. async (c) => {
  862. const diff = await Session.diff(c.req.valid("param").id)
  863. return c.json(diff)
  864. },
  865. )
  866. .get(
  867. "/session/:id/message/:messageID",
  868. describeRoute({
  869. description: "Get a message from a session",
  870. operationId: "session.message",
  871. responses: {
  872. 200: {
  873. description: "Message",
  874. content: {
  875. "application/json": {
  876. schema: resolver(
  877. z.object({
  878. info: MessageV2.Info,
  879. parts: MessageV2.Part.array(),
  880. }),
  881. ),
  882. },
  883. },
  884. },
  885. ...errors(400, 404),
  886. },
  887. }),
  888. validator(
  889. "param",
  890. z.object({
  891. id: z.string().meta({ description: "Session ID" }),
  892. messageID: z.string().meta({ description: "Message ID" }),
  893. }),
  894. ),
  895. async (c) => {
  896. const params = c.req.valid("param")
  897. const message = await MessageV2.get({
  898. sessionID: params.id,
  899. messageID: params.messageID,
  900. })
  901. return c.json(message)
  902. },
  903. )
  904. .post(
  905. "/session/:id/message",
  906. describeRoute({
  907. description: "Create and send a new message to a session",
  908. operationId: "session.prompt",
  909. responses: {
  910. 200: {
  911. description: "Created message",
  912. content: {
  913. "application/json": {
  914. schema: resolver(
  915. z.object({
  916. info: MessageV2.Assistant,
  917. parts: MessageV2.Part.array(),
  918. }),
  919. ),
  920. },
  921. },
  922. },
  923. ...errors(400, 404),
  924. },
  925. }),
  926. validator(
  927. "param",
  928. z.object({
  929. id: z.string().meta({ description: "Session ID" }),
  930. }),
  931. ),
  932. validator("json", SessionPrompt.PromptInput.omit({ sessionID: true })),
  933. async (c) => {
  934. c.status(200)
  935. c.header("Content-Type", "application/json")
  936. return stream(c, async (stream) => {
  937. const sessionID = c.req.valid("param").id
  938. const body = c.req.valid("json")
  939. const msg = await SessionPrompt.prompt({ ...body, sessionID })
  940. stream.write(JSON.stringify(msg))
  941. })
  942. },
  943. )
  944. .post(
  945. "/session/:id/command",
  946. describeRoute({
  947. description: "Send a new command to a session",
  948. operationId: "session.command",
  949. responses: {
  950. 200: {
  951. description: "Created message",
  952. content: {
  953. "application/json": {
  954. schema: resolver(
  955. z.object({
  956. info: MessageV2.Assistant,
  957. parts: MessageV2.Part.array(),
  958. }),
  959. ),
  960. },
  961. },
  962. },
  963. ...errors(400, 404),
  964. },
  965. }),
  966. validator(
  967. "param",
  968. z.object({
  969. id: z.string().meta({ description: "Session ID" }),
  970. }),
  971. ),
  972. validator("json", SessionPrompt.CommandInput.omit({ sessionID: true })),
  973. async (c) => {
  974. const sessionID = c.req.valid("param").id
  975. const body = c.req.valid("json")
  976. const msg = await SessionPrompt.command({ ...body, sessionID })
  977. return c.json(msg)
  978. },
  979. )
  980. .post(
  981. "/session/:id/shell",
  982. describeRoute({
  983. description: "Run a shell command",
  984. operationId: "session.shell",
  985. responses: {
  986. 200: {
  987. description: "Created message",
  988. content: {
  989. "application/json": {
  990. schema: resolver(MessageV2.Assistant),
  991. },
  992. },
  993. },
  994. ...errors(400, 404),
  995. },
  996. }),
  997. validator(
  998. "param",
  999. z.object({
  1000. id: z.string().meta({ description: "Session ID" }),
  1001. }),
  1002. ),
  1003. validator("json", SessionPrompt.ShellInput.omit({ sessionID: true })),
  1004. async (c) => {
  1005. const sessionID = c.req.valid("param").id
  1006. const body = c.req.valid("json")
  1007. const msg = await SessionPrompt.shell({ ...body, sessionID })
  1008. return c.json(msg)
  1009. },
  1010. )
  1011. .post(
  1012. "/session/:id/revert",
  1013. describeRoute({
  1014. description: "Revert a message",
  1015. operationId: "session.revert",
  1016. responses: {
  1017. 200: {
  1018. description: "Updated session",
  1019. content: {
  1020. "application/json": {
  1021. schema: resolver(Session.Info),
  1022. },
  1023. },
  1024. },
  1025. ...errors(400, 404),
  1026. },
  1027. }),
  1028. validator(
  1029. "param",
  1030. z.object({
  1031. id: z.string(),
  1032. }),
  1033. ),
  1034. validator("json", SessionRevert.RevertInput.omit({ sessionID: true })),
  1035. async (c) => {
  1036. const id = c.req.valid("param").id
  1037. log.info("revert", c.req.valid("json"))
  1038. const session = await SessionRevert.revert({
  1039. sessionID: id,
  1040. ...c.req.valid("json"),
  1041. })
  1042. return c.json(session)
  1043. },
  1044. )
  1045. .post(
  1046. "/session/:id/unrevert",
  1047. describeRoute({
  1048. description: "Restore all reverted messages",
  1049. operationId: "session.unrevert",
  1050. responses: {
  1051. 200: {
  1052. description: "Updated session",
  1053. content: {
  1054. "application/json": {
  1055. schema: resolver(Session.Info),
  1056. },
  1057. },
  1058. },
  1059. ...errors(400, 404),
  1060. },
  1061. }),
  1062. validator(
  1063. "param",
  1064. z.object({
  1065. id: z.string(),
  1066. }),
  1067. ),
  1068. async (c) => {
  1069. const id = c.req.valid("param").id
  1070. const session = await SessionRevert.unrevert({ sessionID: id })
  1071. return c.json(session)
  1072. },
  1073. )
  1074. .post(
  1075. "/session/:id/permissions/:permissionID",
  1076. describeRoute({
  1077. description: "Respond to a permission request",
  1078. responses: {
  1079. 200: {
  1080. description: "Permission processed successfully",
  1081. content: {
  1082. "application/json": {
  1083. schema: resolver(z.boolean()),
  1084. },
  1085. },
  1086. },
  1087. ...errors(400, 404),
  1088. },
  1089. }),
  1090. validator(
  1091. "param",
  1092. z.object({
  1093. id: z.string(),
  1094. permissionID: z.string(),
  1095. }),
  1096. ),
  1097. validator("json", z.object({ response: Permission.Response })),
  1098. async (c) => {
  1099. const params = c.req.valid("param")
  1100. const id = params.id
  1101. const permissionID = params.permissionID
  1102. Permission.respond({
  1103. sessionID: id,
  1104. permissionID,
  1105. response: c.req.valid("json").response,
  1106. })
  1107. return c.json(true)
  1108. },
  1109. )
  1110. .get(
  1111. "/command",
  1112. describeRoute({
  1113. description: "List all commands",
  1114. operationId: "command.list",
  1115. responses: {
  1116. 200: {
  1117. description: "List of commands",
  1118. content: {
  1119. "application/json": {
  1120. schema: resolver(Command.Info.array()),
  1121. },
  1122. },
  1123. },
  1124. },
  1125. }),
  1126. async (c) => {
  1127. const commands = await Command.list()
  1128. return c.json(commands)
  1129. },
  1130. )
  1131. .get(
  1132. "/config/providers",
  1133. describeRoute({
  1134. description: "List all providers",
  1135. operationId: "config.providers",
  1136. responses: {
  1137. 200: {
  1138. description: "List of providers",
  1139. content: {
  1140. "application/json": {
  1141. schema: resolver(
  1142. z.object({
  1143. providers: ModelsDev.Provider.array(),
  1144. default: z.record(z.string(), z.string()),
  1145. }),
  1146. ),
  1147. },
  1148. },
  1149. },
  1150. },
  1151. }),
  1152. async (c) => {
  1153. using _ = log.time("providers")
  1154. const providers = await Provider.list().then((x) => mapValues(x, (item) => item.info))
  1155. return c.json({
  1156. providers: Object.values(providers),
  1157. default: mapValues(providers, (item) => Provider.sort(Object.values(item.models))[0].id),
  1158. })
  1159. },
  1160. )
  1161. .get(
  1162. "/find",
  1163. describeRoute({
  1164. description: "Find text in files",
  1165. operationId: "find.text",
  1166. responses: {
  1167. 200: {
  1168. description: "Matches",
  1169. content: {
  1170. "application/json": {
  1171. schema: resolver(Ripgrep.Match.shape.data.array()),
  1172. },
  1173. },
  1174. },
  1175. },
  1176. }),
  1177. validator(
  1178. "query",
  1179. z.object({
  1180. pattern: z.string(),
  1181. }),
  1182. ),
  1183. async (c) => {
  1184. const pattern = c.req.valid("query").pattern
  1185. const result = await Ripgrep.search({
  1186. cwd: Instance.directory,
  1187. pattern,
  1188. limit: 10,
  1189. })
  1190. return c.json(result)
  1191. },
  1192. )
  1193. .get(
  1194. "/find/file",
  1195. describeRoute({
  1196. description: "Find files",
  1197. operationId: "find.files",
  1198. responses: {
  1199. 200: {
  1200. description: "File paths",
  1201. content: {
  1202. "application/json": {
  1203. schema: resolver(z.string().array()),
  1204. },
  1205. },
  1206. },
  1207. },
  1208. }),
  1209. validator(
  1210. "query",
  1211. z.object({
  1212. query: z.string(),
  1213. dirs: z.enum(["true", "false"]).optional(),
  1214. }),
  1215. ),
  1216. async (c) => {
  1217. const query = c.req.valid("query").query
  1218. const dirs = c.req.valid("query").dirs
  1219. const results = await File.search({
  1220. query,
  1221. limit: 10,
  1222. dirs: dirs !== "false",
  1223. })
  1224. return c.json(results)
  1225. },
  1226. )
  1227. .get(
  1228. "/find/symbol",
  1229. describeRoute({
  1230. description: "Find workspace symbols",
  1231. operationId: "find.symbols",
  1232. responses: {
  1233. 200: {
  1234. description: "Symbols",
  1235. content: {
  1236. "application/json": {
  1237. schema: resolver(LSP.Symbol.array()),
  1238. },
  1239. },
  1240. },
  1241. },
  1242. }),
  1243. validator(
  1244. "query",
  1245. z.object({
  1246. query: z.string(),
  1247. }),
  1248. ),
  1249. async (c) => {
  1250. /*
  1251. const query = c.req.valid("query").query
  1252. const result = await LSP.workspaceSymbol(query)
  1253. return c.json(result)
  1254. */
  1255. return c.json([])
  1256. },
  1257. )
  1258. .get(
  1259. "/file",
  1260. describeRoute({
  1261. description: "List files and directories",
  1262. operationId: "file.list",
  1263. responses: {
  1264. 200: {
  1265. description: "Files and directories",
  1266. content: {
  1267. "application/json": {
  1268. schema: resolver(File.Node.array()),
  1269. },
  1270. },
  1271. },
  1272. },
  1273. }),
  1274. validator(
  1275. "query",
  1276. z.object({
  1277. path: z.string(),
  1278. }),
  1279. ),
  1280. async (c) => {
  1281. const path = c.req.valid("query").path
  1282. const content = await File.list(path)
  1283. return c.json(content)
  1284. },
  1285. )
  1286. .get(
  1287. "/file/content",
  1288. describeRoute({
  1289. description: "Read a file",
  1290. operationId: "file.read",
  1291. responses: {
  1292. 200: {
  1293. description: "File content",
  1294. content: {
  1295. "application/json": {
  1296. schema: resolver(File.Content),
  1297. },
  1298. },
  1299. },
  1300. },
  1301. }),
  1302. validator(
  1303. "query",
  1304. z.object({
  1305. path: z.string(),
  1306. }),
  1307. ),
  1308. async (c) => {
  1309. const path = c.req.valid("query").path
  1310. const content = await File.read(path)
  1311. return c.json(content)
  1312. },
  1313. )
  1314. .get(
  1315. "/file/status",
  1316. describeRoute({
  1317. description: "Get file status",
  1318. operationId: "file.status",
  1319. responses: {
  1320. 200: {
  1321. description: "File status",
  1322. content: {
  1323. "application/json": {
  1324. schema: resolver(File.Info.array()),
  1325. },
  1326. },
  1327. },
  1328. },
  1329. }),
  1330. async (c) => {
  1331. const content = await File.status()
  1332. return c.json(content)
  1333. },
  1334. )
  1335. .post(
  1336. "/log",
  1337. describeRoute({
  1338. description: "Write a log entry to the server logs",
  1339. operationId: "app.log",
  1340. responses: {
  1341. 200: {
  1342. description: "Log entry written successfully",
  1343. content: {
  1344. "application/json": {
  1345. schema: resolver(z.boolean()),
  1346. },
  1347. },
  1348. },
  1349. ...errors(400),
  1350. },
  1351. }),
  1352. validator(
  1353. "json",
  1354. z.object({
  1355. service: z.string().meta({ description: "Service name for the log entry" }),
  1356. level: z.enum(["debug", "info", "error", "warn"]).meta({ description: "Log level" }),
  1357. message: z.string().meta({ description: "Log message" }),
  1358. extra: z
  1359. .record(z.string(), z.any())
  1360. .optional()
  1361. .meta({ description: "Additional metadata for the log entry" }),
  1362. }),
  1363. ),
  1364. async (c) => {
  1365. const { service, level, message, extra } = c.req.valid("json")
  1366. const logger = Log.create({ service })
  1367. switch (level) {
  1368. case "debug":
  1369. logger.debug(message, extra)
  1370. break
  1371. case "info":
  1372. logger.info(message, extra)
  1373. break
  1374. case "error":
  1375. logger.error(message, extra)
  1376. break
  1377. case "warn":
  1378. logger.warn(message, extra)
  1379. break
  1380. }
  1381. return c.json(true)
  1382. },
  1383. )
  1384. .get(
  1385. "/agent",
  1386. describeRoute({
  1387. description: "List all agents",
  1388. operationId: "app.agents",
  1389. responses: {
  1390. 200: {
  1391. description: "List of agents",
  1392. content: {
  1393. "application/json": {
  1394. schema: resolver(Agent.Info.array()),
  1395. },
  1396. },
  1397. },
  1398. },
  1399. }),
  1400. async (c) => {
  1401. const modes = await Agent.list()
  1402. return c.json(modes)
  1403. },
  1404. )
  1405. .get(
  1406. "/mcp",
  1407. describeRoute({
  1408. description: "Get MCP server status",
  1409. operationId: "mcp.status",
  1410. responses: {
  1411. 200: {
  1412. description: "MCP server status",
  1413. content: {
  1414. "application/json": {
  1415. schema: resolver(z.record(z.string(), MCP.Status)),
  1416. },
  1417. },
  1418. },
  1419. },
  1420. }),
  1421. async (c) => {
  1422. return c.json(await MCP.status())
  1423. },
  1424. )
  1425. .post(
  1426. "/mcp",
  1427. describeRoute({
  1428. description: "Add MCP server dynamically",
  1429. operationId: "mcp.add",
  1430. responses: {
  1431. 200: {
  1432. description: "MCP server added successfully",
  1433. content: {
  1434. "application/json": {
  1435. schema: resolver(z.record(z.string(), MCP.Status)),
  1436. },
  1437. },
  1438. },
  1439. ...errors(400),
  1440. },
  1441. }),
  1442. validator(
  1443. "json",
  1444. z.object({
  1445. name: z.string(),
  1446. config: Config.Mcp,
  1447. }),
  1448. ),
  1449. async (c) => {
  1450. const { name, config } = c.req.valid("json")
  1451. const result = await MCP.add(name, config)
  1452. return c.json(result.status)
  1453. },
  1454. )
  1455. .get(
  1456. "/lsp",
  1457. describeRoute({
  1458. description: "Get LSP server status",
  1459. operationId: "lsp.status",
  1460. responses: {
  1461. 200: {
  1462. description: "LSP server status",
  1463. content: {
  1464. "application/json": {
  1465. schema: resolver(LSP.Status.array()),
  1466. },
  1467. },
  1468. },
  1469. },
  1470. }),
  1471. async (c) => {
  1472. return c.json(await LSP.status())
  1473. },
  1474. )
  1475. .get(
  1476. "/formatter",
  1477. describeRoute({
  1478. description: "Get formatter status",
  1479. operationId: "formatter.status",
  1480. responses: {
  1481. 200: {
  1482. description: "Formatter status",
  1483. content: {
  1484. "application/json": {
  1485. schema: resolver(Format.Status.array()),
  1486. },
  1487. },
  1488. },
  1489. },
  1490. }),
  1491. async (c) => {
  1492. return c.json(await Format.status())
  1493. },
  1494. )
  1495. .post(
  1496. "/tui/append-prompt",
  1497. describeRoute({
  1498. description: "Append prompt to the TUI",
  1499. operationId: "tui.appendPrompt",
  1500. responses: {
  1501. 200: {
  1502. description: "Prompt processed successfully",
  1503. content: {
  1504. "application/json": {
  1505. schema: resolver(z.boolean()),
  1506. },
  1507. },
  1508. },
  1509. ...errors(400),
  1510. },
  1511. }),
  1512. validator("json", TuiEvent.PromptAppend.properties),
  1513. async (c) => {
  1514. await Bus.publish(TuiEvent.PromptAppend, c.req.valid("json"))
  1515. return c.json(true)
  1516. },
  1517. )
  1518. .post(
  1519. "/tui/open-help",
  1520. describeRoute({
  1521. description: "Open the help dialog",
  1522. operationId: "tui.openHelp",
  1523. responses: {
  1524. 200: {
  1525. description: "Help dialog opened successfully",
  1526. content: {
  1527. "application/json": {
  1528. schema: resolver(z.boolean()),
  1529. },
  1530. },
  1531. },
  1532. },
  1533. }),
  1534. async (c) => {
  1535. // TODO: open dialog
  1536. return c.json(true)
  1537. },
  1538. )
  1539. .post(
  1540. "/tui/open-sessions",
  1541. describeRoute({
  1542. description: "Open the session dialog",
  1543. operationId: "tui.openSessions",
  1544. responses: {
  1545. 200: {
  1546. description: "Session dialog opened successfully",
  1547. content: {
  1548. "application/json": {
  1549. schema: resolver(z.boolean()),
  1550. },
  1551. },
  1552. },
  1553. },
  1554. }),
  1555. async (c) => {
  1556. await Bus.publish(TuiEvent.CommandExecute, {
  1557. command: "session.list",
  1558. })
  1559. return c.json(true)
  1560. },
  1561. )
  1562. .post(
  1563. "/tui/open-themes",
  1564. describeRoute({
  1565. description: "Open the theme dialog",
  1566. operationId: "tui.openThemes",
  1567. responses: {
  1568. 200: {
  1569. description: "Theme dialog opened successfully",
  1570. content: {
  1571. "application/json": {
  1572. schema: resolver(z.boolean()),
  1573. },
  1574. },
  1575. },
  1576. },
  1577. }),
  1578. async (c) => {
  1579. await Bus.publish(TuiEvent.CommandExecute, {
  1580. command: "session.list",
  1581. })
  1582. return c.json(true)
  1583. },
  1584. )
  1585. .post(
  1586. "/tui/open-models",
  1587. describeRoute({
  1588. description: "Open the model dialog",
  1589. operationId: "tui.openModels",
  1590. responses: {
  1591. 200: {
  1592. description: "Model dialog opened successfully",
  1593. content: {
  1594. "application/json": {
  1595. schema: resolver(z.boolean()),
  1596. },
  1597. },
  1598. },
  1599. },
  1600. }),
  1601. async (c) => {
  1602. await Bus.publish(TuiEvent.CommandExecute, {
  1603. command: "model.list",
  1604. })
  1605. return c.json(true)
  1606. },
  1607. )
  1608. .post(
  1609. "/tui/submit-prompt",
  1610. describeRoute({
  1611. description: "Submit the prompt",
  1612. operationId: "tui.submitPrompt",
  1613. responses: {
  1614. 200: {
  1615. description: "Prompt submitted successfully",
  1616. content: {
  1617. "application/json": {
  1618. schema: resolver(z.boolean()),
  1619. },
  1620. },
  1621. },
  1622. },
  1623. }),
  1624. async (c) => {
  1625. await Bus.publish(TuiEvent.CommandExecute, {
  1626. command: "prompt.submit",
  1627. })
  1628. return c.json(true)
  1629. },
  1630. )
  1631. .post(
  1632. "/tui/clear-prompt",
  1633. describeRoute({
  1634. description: "Clear the prompt",
  1635. operationId: "tui.clearPrompt",
  1636. responses: {
  1637. 200: {
  1638. description: "Prompt cleared successfully",
  1639. content: {
  1640. "application/json": {
  1641. schema: resolver(z.boolean()),
  1642. },
  1643. },
  1644. },
  1645. },
  1646. }),
  1647. async (c) => {
  1648. await Bus.publish(TuiEvent.CommandExecute, {
  1649. command: "prompt.clear",
  1650. })
  1651. return c.json(true)
  1652. },
  1653. )
  1654. .post(
  1655. "/tui/execute-command",
  1656. describeRoute({
  1657. description: "Execute a TUI command (e.g. agent_cycle)",
  1658. operationId: "tui.executeCommand",
  1659. responses: {
  1660. 200: {
  1661. description: "Command executed successfully",
  1662. content: {
  1663. "application/json": {
  1664. schema: resolver(z.boolean()),
  1665. },
  1666. },
  1667. },
  1668. ...errors(400),
  1669. },
  1670. }),
  1671. validator("json", z.object({ command: z.string() })),
  1672. async (c) => {
  1673. const command = c.req.valid("json").command
  1674. await Bus.publish(TuiEvent.CommandExecute, {
  1675. // @ts-expect-error
  1676. command: {
  1677. session_new: "session.new",
  1678. session_share: "session.share",
  1679. session_interrupt: "session.interrupt",
  1680. session_compact: "session.compact",
  1681. messages_page_up: "session.page.up",
  1682. messages_page_down: "session.page.down",
  1683. messages_half_page_up: "session.half.page.up",
  1684. messages_half_page_down: "session.half.page.down",
  1685. messages_first: "session.first",
  1686. messages_last: "session.last",
  1687. agent_cycle: "agent.cycle",
  1688. }[command],
  1689. })
  1690. return c.json(true)
  1691. },
  1692. )
  1693. .post(
  1694. "/tui/show-toast",
  1695. describeRoute({
  1696. description: "Show a toast notification in the TUI",
  1697. operationId: "tui.showToast",
  1698. responses: {
  1699. 200: {
  1700. description: "Toast notification shown successfully",
  1701. content: {
  1702. "application/json": {
  1703. schema: resolver(z.boolean()),
  1704. },
  1705. },
  1706. },
  1707. },
  1708. }),
  1709. validator("json", TuiEvent.ToastShow.properties),
  1710. async (c) => {
  1711. await Bus.publish(TuiEvent.ToastShow, c.req.valid("json"))
  1712. return c.json(true)
  1713. },
  1714. )
  1715. .post(
  1716. "/tui/publish",
  1717. describeRoute({
  1718. description: "Publish a TUI event",
  1719. operationId: "tui.publish",
  1720. responses: {
  1721. 200: {
  1722. description: "Event published successfully",
  1723. content: {
  1724. "application/json": {
  1725. schema: resolver(z.boolean()),
  1726. },
  1727. },
  1728. },
  1729. ...errors(400),
  1730. },
  1731. }),
  1732. validator(
  1733. "json",
  1734. z.union(
  1735. Object.values(TuiEvent).map((def) => {
  1736. return z
  1737. .object({
  1738. type: z.literal(def.type),
  1739. properties: def.properties,
  1740. })
  1741. .meta({
  1742. ref: "Event" + "." + def.type,
  1743. })
  1744. }),
  1745. ),
  1746. ),
  1747. async (c) => {
  1748. const evt = c.req.valid("json")
  1749. await Bus.publish(Object.values(TuiEvent).find((def) => def.type === evt.type)!, evt.properties)
  1750. return c.json(true)
  1751. },
  1752. )
  1753. .route("/tui/control", TuiRoute)
  1754. .put(
  1755. "/auth/:id",
  1756. describeRoute({
  1757. description: "Set authentication credentials",
  1758. operationId: "auth.set",
  1759. responses: {
  1760. 200: {
  1761. description: "Successfully set authentication credentials",
  1762. content: {
  1763. "application/json": {
  1764. schema: resolver(z.boolean()),
  1765. },
  1766. },
  1767. },
  1768. ...errors(400),
  1769. },
  1770. }),
  1771. validator(
  1772. "param",
  1773. z.object({
  1774. id: z.string(),
  1775. }),
  1776. ),
  1777. validator("json", Auth.Info),
  1778. async (c) => {
  1779. const id = c.req.valid("param").id
  1780. const info = c.req.valid("json")
  1781. await Auth.set(id, info)
  1782. return c.json(true)
  1783. },
  1784. )
  1785. .get(
  1786. "/event",
  1787. describeRoute({
  1788. description: "Get events",
  1789. operationId: "event.subscribe",
  1790. responses: {
  1791. 200: {
  1792. description: "Event stream",
  1793. content: {
  1794. "text/event-stream": {
  1795. schema: resolver(Bus.payloads()),
  1796. },
  1797. },
  1798. },
  1799. },
  1800. }),
  1801. async (c) => {
  1802. log.info("event connected")
  1803. return streamSSE(c, async (stream) => {
  1804. stream.writeSSE({
  1805. data: JSON.stringify({
  1806. type: "server.connected",
  1807. properties: {},
  1808. }),
  1809. })
  1810. const unsub = Bus.subscribeAll(async (event) => {
  1811. await stream.writeSSE({
  1812. data: JSON.stringify(event),
  1813. })
  1814. })
  1815. await new Promise<void>((resolve) => {
  1816. stream.onAbort(() => {
  1817. unsub()
  1818. resolve()
  1819. log.info("event disconnected")
  1820. })
  1821. })
  1822. })
  1823. },
  1824. )
  1825. .all("/*", async (c) => {
  1826. return proxy(`https://desktop.dev.opencode.ai${c.req.path}`, {
  1827. ...c.req,
  1828. headers: {
  1829. host: "desktop.dev.opencode.ai",
  1830. },
  1831. })
  1832. }),
  1833. )
  1834. export async function openapi() {
  1835. const result = await generateSpecs(App(), {
  1836. documentation: {
  1837. info: {
  1838. title: "opencode",
  1839. version: "1.0.0",
  1840. description: "opencode api",
  1841. },
  1842. openapi: "3.1.1",
  1843. },
  1844. })
  1845. return result
  1846. }
  1847. export function listen(opts: { port: number; hostname: string }) {
  1848. const server = Bun.serve({
  1849. port: opts.port,
  1850. hostname: opts.hostname,
  1851. idleTimeout: 0,
  1852. fetch: App().fetch,
  1853. })
  1854. return server
  1855. }
  1856. }