index.ts 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731
  1. import path from "path"
  2. import { spawn } from "child_process"
  3. import { Decimal } from "decimal.js"
  4. import { z, ZodSchema } from "zod"
  5. import {
  6. generateText,
  7. LoadAPIKeyError,
  8. streamText,
  9. tool,
  10. wrapLanguageModel,
  11. type Tool as AITool,
  12. type LanguageModelUsage,
  13. type ProviderMetadata,
  14. type ModelMessage,
  15. type StreamTextResult,
  16. } from "ai"
  17. import PROMPT_INITIALIZE from "../session/prompt/initialize.txt"
  18. import PROMPT_PLAN from "../session/prompt/plan.txt"
  19. import BUILD_SWITCH from "../session/prompt/build-switch.txt"
  20. import { App } from "../app/app"
  21. import { Bus } from "../bus"
  22. import { Config } from "../config/config"
  23. import { Flag } from "../flag/flag"
  24. import { Identifier } from "../id/id"
  25. import { Installation } from "../installation"
  26. import { MCP } from "../mcp"
  27. import { Provider } from "../provider/provider"
  28. import { ProviderTransform } from "../provider/transform"
  29. import type { ModelsDev } from "../provider/models"
  30. import { Share } from "../share/share"
  31. import { Snapshot } from "../snapshot"
  32. import { Storage } from "../storage/storage"
  33. import { Log } from "../util/log"
  34. import { NamedError } from "../util/error"
  35. import { SystemPrompt } from "./system"
  36. import { FileTime } from "../file/time"
  37. import { MessageV2 } from "./message-v2"
  38. import { LSP } from "../lsp"
  39. import { ReadTool } from "../tool/read"
  40. import { mergeDeep, pipe, splitWhen } from "remeda"
  41. import { ToolRegistry } from "../tool/registry"
  42. import { Plugin } from "../plugin"
  43. import { Agent } from "../agent/agent"
  44. import { Permission } from "../permission"
  45. import { Wildcard } from "../util/wildcard"
  46. import { ulid } from "ulid"
  47. import { defer } from "../util/defer"
  48. import { Command } from "../command"
  49. import { $ } from "bun"
  50. export namespace Session {
  51. const log = Log.create({ service: "session" })
  52. const OUTPUT_TOKEN_MAX = 32_000
  53. const parentSessionTitlePrefix = "New session - "
  54. const childSessionTitlePrefix = "Child session - "
  55. function createDefaultTitle(isChild = false) {
  56. return (isChild ? childSessionTitlePrefix : parentSessionTitlePrefix) + new Date().toISOString()
  57. }
  58. function isDefaultTitle(title: string) {
  59. return title.startsWith(parentSessionTitlePrefix)
  60. }
  61. export const Info = z
  62. .object({
  63. id: Identifier.schema("session"),
  64. parentID: Identifier.schema("session").optional(),
  65. share: z
  66. .object({
  67. url: z.string(),
  68. })
  69. .optional(),
  70. title: z.string(),
  71. version: z.string(),
  72. time: z.object({
  73. created: z.number(),
  74. updated: z.number(),
  75. }),
  76. revert: z
  77. .object({
  78. messageID: z.string(),
  79. partID: z.string().optional(),
  80. snapshot: z.string().optional(),
  81. diff: z.string().optional(),
  82. })
  83. .optional(),
  84. })
  85. .openapi({
  86. ref: "Session",
  87. })
  88. export type Info = z.output<typeof Info>
  89. export const ShareInfo = z
  90. .object({
  91. secret: z.string(),
  92. url: z.string(),
  93. })
  94. .openapi({
  95. ref: "SessionShare",
  96. })
  97. export type ShareInfo = z.output<typeof ShareInfo>
  98. export const Event = {
  99. Updated: Bus.event(
  100. "session.updated",
  101. z.object({
  102. info: Info,
  103. }),
  104. ),
  105. Deleted: Bus.event(
  106. "session.deleted",
  107. z.object({
  108. info: Info,
  109. }),
  110. ),
  111. Idle: Bus.event(
  112. "session.idle",
  113. z.object({
  114. sessionID: z.string(),
  115. }),
  116. ),
  117. Error: Bus.event(
  118. "session.error",
  119. z.object({
  120. sessionID: z.string().optional(),
  121. error: MessageV2.Assistant.shape.error,
  122. }),
  123. ),
  124. }
  125. const state = App.state(
  126. "session",
  127. () => {
  128. const sessions = new Map<string, Info>()
  129. const messages = new Map<string, MessageV2.Info[]>()
  130. const pending = new Map<string, AbortController>()
  131. const autoCompacting = new Map<string, boolean>()
  132. const queued = new Map<
  133. string,
  134. {
  135. input: ChatInput
  136. message: MessageV2.User
  137. parts: MessageV2.Part[]
  138. processed: boolean
  139. callback: (input: { info: MessageV2.Assistant; parts: MessageV2.Part[] }) => void
  140. }[]
  141. >()
  142. return {
  143. sessions,
  144. messages,
  145. pending,
  146. autoCompacting,
  147. queued,
  148. }
  149. },
  150. async (state) => {
  151. for (const [_, controller] of state.pending) {
  152. controller.abort()
  153. }
  154. },
  155. )
  156. export async function create(parentID?: string, title?: string) {
  157. const result: Info = {
  158. id: Identifier.descending("session"),
  159. version: Installation.VERSION,
  160. parentID,
  161. title: title ?? createDefaultTitle(!!parentID),
  162. time: {
  163. created: Date.now(),
  164. updated: Date.now(),
  165. },
  166. }
  167. log.info("created", result)
  168. state().sessions.set(result.id, result)
  169. await Storage.writeJSON("session/info/" + result.id, result)
  170. const cfg = await Config.get()
  171. if (!result.parentID && (Flag.OPENCODE_AUTO_SHARE || cfg.share === "auto"))
  172. share(result.id)
  173. .then((share) => {
  174. update(result.id, (draft) => {
  175. draft.share = share
  176. })
  177. })
  178. .catch(() => {
  179. // Silently ignore sharing errors during session creation
  180. })
  181. Bus.publish(Event.Updated, {
  182. info: result,
  183. })
  184. return result
  185. }
  186. export async function get(id: string) {
  187. const result = state().sessions.get(id)
  188. if (result) {
  189. return result
  190. }
  191. const read = await Storage.readJSON<Info>("session/info/" + id)
  192. state().sessions.set(id, read)
  193. return read as Info
  194. }
  195. export async function getShare(id: string) {
  196. return Storage.readJSON<ShareInfo>("session/share/" + id)
  197. }
  198. export async function share(id: string) {
  199. const cfg = await Config.get()
  200. if (cfg.share === "disabled") {
  201. throw new Error("Sharing is disabled in configuration")
  202. }
  203. const session = await get(id)
  204. if (session.share) return session.share
  205. const share = await Share.create(id)
  206. await update(id, (draft) => {
  207. draft.share = {
  208. url: share.url,
  209. }
  210. })
  211. await Storage.writeJSON<ShareInfo>("session/share/" + id, share)
  212. await Share.sync("session/info/" + id, session)
  213. for (const msg of await messages(id)) {
  214. await Share.sync("session/message/" + id + "/" + msg.info.id, msg.info)
  215. for (const part of msg.parts) {
  216. await Share.sync("session/part/" + id + "/" + msg.info.id + "/" + part.id, part)
  217. }
  218. }
  219. return share
  220. }
  221. export async function unshare(id: string) {
  222. const share = await getShare(id)
  223. if (!share) return
  224. await Storage.remove("session/share/" + id)
  225. await update(id, (draft) => {
  226. draft.share = undefined
  227. })
  228. await Share.remove(id, share.secret)
  229. }
  230. export async function update(id: string, editor: (session: Info) => void) {
  231. const { sessions } = state()
  232. const session = await get(id)
  233. if (!session) return
  234. editor(session)
  235. session.time.updated = Date.now()
  236. sessions.set(id, session)
  237. await Storage.writeJSON("session/info/" + id, session)
  238. Bus.publish(Event.Updated, {
  239. info: session,
  240. })
  241. return session
  242. }
  243. export async function messages(sessionID: string) {
  244. const result = [] as {
  245. info: MessageV2.Info
  246. parts: MessageV2.Part[]
  247. }[]
  248. for (const p of await Storage.list("session/message/" + sessionID)) {
  249. const read = await Storage.readJSON<MessageV2.Info>(p)
  250. result.push({
  251. info: read,
  252. parts: await getParts(sessionID, read.id),
  253. })
  254. }
  255. result.sort((a, b) => (a.info.id > b.info.id ? 1 : -1))
  256. return result
  257. }
  258. export async function getMessage(sessionID: string, messageID: string) {
  259. return {
  260. info: await Storage.readJSON<MessageV2.Info>("session/message/" + sessionID + "/" + messageID),
  261. parts: await getParts(sessionID, messageID),
  262. }
  263. }
  264. export async function getParts(sessionID: string, messageID: string) {
  265. const result = [] as MessageV2.Part[]
  266. for (const item of await Storage.list("session/part/" + sessionID + "/" + messageID)) {
  267. const read = await Storage.readJSON<MessageV2.Part>(item)
  268. result.push(read)
  269. }
  270. result.sort((a, b) => (a.id > b.id ? 1 : -1))
  271. return result
  272. }
  273. export async function* list() {
  274. for (const item of await Storage.list("session/info")) {
  275. const sessionID = path.basename(item, ".json")
  276. yield get(sessionID)
  277. }
  278. }
  279. export async function children(parentID: string) {
  280. const result = [] as Session.Info[]
  281. for (const item of await Storage.list("session/info")) {
  282. const sessionID = path.basename(item, ".json")
  283. const session = await get(sessionID)
  284. if (session.parentID !== parentID) continue
  285. result.push(session)
  286. }
  287. return result
  288. }
  289. export function abort(sessionID: string) {
  290. const controller = state().pending.get(sessionID)
  291. if (!controller) return false
  292. log.info("aborting", {
  293. sessionID,
  294. })
  295. controller.abort()
  296. state().pending.delete(sessionID)
  297. return true
  298. }
  299. export async function remove(sessionID: string, emitEvent = true) {
  300. try {
  301. abort(sessionID)
  302. const session = await get(sessionID)
  303. for (const child of await children(sessionID)) {
  304. await remove(child.id, false)
  305. }
  306. await unshare(sessionID).catch(() => {})
  307. await Storage.remove(`session/info/${sessionID}`).catch(() => {})
  308. await Storage.removeDir(`session/message/${sessionID}/`).catch(() => {})
  309. state().sessions.delete(sessionID)
  310. state().messages.delete(sessionID)
  311. if (emitEvent) {
  312. Bus.publish(Event.Deleted, {
  313. info: session,
  314. })
  315. }
  316. } catch (e) {
  317. log.error(e)
  318. }
  319. }
  320. async function updateMessage(msg: MessageV2.Info) {
  321. await Storage.writeJSON("session/message/" + msg.sessionID + "/" + msg.id, msg)
  322. Bus.publish(MessageV2.Event.Updated, {
  323. info: msg,
  324. })
  325. }
  326. async function updatePart(part: MessageV2.Part) {
  327. await Storage.writeJSON(["session", "part", part.sessionID, part.messageID, part.id].join("/"), part)
  328. Bus.publish(MessageV2.Event.PartUpdated, {
  329. part,
  330. })
  331. return part
  332. }
  333. export const ChatInput = z.object({
  334. sessionID: Identifier.schema("session"),
  335. messageID: Identifier.schema("message").optional(),
  336. providerID: z.string(),
  337. modelID: z.string(),
  338. agent: z.string().optional(),
  339. system: z.string().optional(),
  340. tools: z.record(z.boolean()).optional(),
  341. parts: z.array(
  342. z.discriminatedUnion("type", [
  343. MessageV2.TextPart.omit({
  344. messageID: true,
  345. sessionID: true,
  346. })
  347. .partial({
  348. id: true,
  349. })
  350. .openapi({
  351. ref: "TextPartInput",
  352. }),
  353. MessageV2.FilePart.omit({
  354. messageID: true,
  355. sessionID: true,
  356. })
  357. .partial({
  358. id: true,
  359. })
  360. .openapi({
  361. ref: "FilePartInput",
  362. }),
  363. MessageV2.AgentPart.omit({
  364. messageID: true,
  365. sessionID: true,
  366. })
  367. .partial({
  368. id: true,
  369. })
  370. .openapi({
  371. ref: "AgentPartInput",
  372. }),
  373. ]),
  374. ),
  375. })
  376. export type ChatInput = z.infer<typeof ChatInput>
  377. export async function chat(
  378. input: z.infer<typeof ChatInput>,
  379. ): Promise<{ info: MessageV2.Assistant; parts: MessageV2.Part[] }> {
  380. const l = log.clone().tag("session", input.sessionID)
  381. l.info("chatting")
  382. const inputAgent = input.agent ?? "build"
  383. // Process revert cleanup first, before creating new messages
  384. const session = await get(input.sessionID)
  385. if (session.revert) {
  386. let msgs = await messages(input.sessionID)
  387. const messageID = session.revert.messageID
  388. const [preserve, remove] = splitWhen(msgs, (x) => x.info.id === messageID)
  389. msgs = preserve
  390. for (const msg of remove) {
  391. await Storage.remove(`session/message/${input.sessionID}/${msg.info.id}`)
  392. await Bus.publish(MessageV2.Event.Removed, { sessionID: input.sessionID, messageID: msg.info.id })
  393. }
  394. const last = preserve.at(-1)
  395. if (session.revert.partID && last) {
  396. const partID = session.revert.partID
  397. const [preserveParts, removeParts] = splitWhen(last.parts, (x) => x.id === partID)
  398. last.parts = preserveParts
  399. for (const part of removeParts) {
  400. await Storage.remove(`session/part/${input.sessionID}/${last.info.id}/${part.id}`)
  401. await Bus.publish(MessageV2.Event.PartRemoved, {
  402. sessionID: input.sessionID,
  403. messageID: last.info.id,
  404. partID: part.id,
  405. })
  406. }
  407. }
  408. await update(input.sessionID, (draft) => {
  409. draft.revert = undefined
  410. })
  411. }
  412. const userMsg: MessageV2.Info = {
  413. id: input.messageID ?? Identifier.ascending("message"),
  414. role: "user",
  415. sessionID: input.sessionID,
  416. time: {
  417. created: Date.now(),
  418. },
  419. }
  420. const app = App.info()
  421. const userParts = await Promise.all(
  422. input.parts.map(async (part): Promise<MessageV2.Part[]> => {
  423. if (part.type === "file") {
  424. const url = new URL(part.url)
  425. switch (url.protocol) {
  426. case "data:":
  427. if (part.mime === "text/plain") {
  428. return [
  429. {
  430. id: Identifier.ascending("part"),
  431. messageID: userMsg.id,
  432. sessionID: input.sessionID,
  433. type: "text",
  434. synthetic: true,
  435. text: `Called the Read tool with the following input: ${JSON.stringify({ filePath: part.filename })}`,
  436. },
  437. {
  438. id: Identifier.ascending("part"),
  439. messageID: userMsg.id,
  440. sessionID: input.sessionID,
  441. type: "text",
  442. synthetic: true,
  443. text: Buffer.from(part.url, "base64url").toString(),
  444. },
  445. {
  446. ...part,
  447. id: part.id ?? Identifier.ascending("part"),
  448. messageID: userMsg.id,
  449. sessionID: input.sessionID,
  450. },
  451. ]
  452. }
  453. break
  454. case "file:":
  455. // have to normalize, symbol search returns absolute paths
  456. // Decode the pathname since URL constructor doesn't automatically decode it
  457. const filePath = decodeURIComponent(url.pathname)
  458. if (part.mime === "text/plain") {
  459. let offset: number | undefined = undefined
  460. let limit: number | undefined = undefined
  461. const range = {
  462. start: url.searchParams.get("start"),
  463. end: url.searchParams.get("end"),
  464. }
  465. if (range.start != null) {
  466. const filePath = part.url.split("?")[0]
  467. let start = parseInt(range.start)
  468. let end = range.end ? parseInt(range.end) : undefined
  469. // some LSP servers (eg, gopls) don't give full range in
  470. // workspace/symbol searches, so we'll try to find the
  471. // symbol in the document to get the full range
  472. if (start === end) {
  473. const symbols = await LSP.documentSymbol(filePath)
  474. for (const symbol of symbols) {
  475. let range: LSP.Range | undefined
  476. if ("range" in symbol) {
  477. range = symbol.range
  478. } else if ("location" in symbol) {
  479. range = symbol.location.range
  480. }
  481. if (range?.start?.line && range?.start?.line === start) {
  482. start = range.start.line
  483. end = range?.end?.line ?? start
  484. break
  485. }
  486. }
  487. offset = Math.max(start - 2, 0)
  488. if (end) {
  489. limit = end - offset + 2
  490. }
  491. }
  492. }
  493. const args = { filePath, offset, limit }
  494. const result = await ReadTool.init().then((t) =>
  495. t.execute(args, {
  496. sessionID: input.sessionID,
  497. abort: new AbortController().signal,
  498. agent: input.agent!,
  499. messageID: userMsg.id,
  500. extra: { bypassCwdCheck: true },
  501. metadata: async () => {},
  502. }),
  503. )
  504. return [
  505. {
  506. id: Identifier.ascending("part"),
  507. messageID: userMsg.id,
  508. sessionID: input.sessionID,
  509. type: "text",
  510. synthetic: true,
  511. text: `Called the Read tool with the following input: ${JSON.stringify(args)}`,
  512. },
  513. {
  514. id: Identifier.ascending("part"),
  515. messageID: userMsg.id,
  516. sessionID: input.sessionID,
  517. type: "text",
  518. synthetic: true,
  519. text: result.output,
  520. },
  521. {
  522. ...part,
  523. id: part.id ?? Identifier.ascending("part"),
  524. messageID: userMsg.id,
  525. sessionID: input.sessionID,
  526. },
  527. ]
  528. }
  529. let file = Bun.file(filePath)
  530. FileTime.read(input.sessionID, filePath)
  531. return [
  532. {
  533. id: Identifier.ascending("part"),
  534. messageID: userMsg.id,
  535. sessionID: input.sessionID,
  536. type: "text",
  537. text: `Called the Read tool with the following input: {\"filePath\":\"${filePath}\"}`,
  538. synthetic: true,
  539. },
  540. {
  541. id: part.id ?? Identifier.ascending("part"),
  542. messageID: userMsg.id,
  543. sessionID: input.sessionID,
  544. type: "file",
  545. url: `data:${part.mime};base64,` + Buffer.from(await file.bytes()).toString("base64"),
  546. mime: part.mime,
  547. filename: part.filename!,
  548. source: part.source,
  549. },
  550. ]
  551. }
  552. }
  553. if (part.type === "agent") {
  554. return [
  555. {
  556. id: Identifier.ascending("part"),
  557. ...part,
  558. messageID: userMsg.id,
  559. sessionID: input.sessionID,
  560. },
  561. {
  562. id: Identifier.ascending("part"),
  563. messageID: userMsg.id,
  564. sessionID: input.sessionID,
  565. type: "text",
  566. synthetic: true,
  567. text:
  568. "Use the above message and context to generate a prompt and call the task tool with subagent: " +
  569. part.name,
  570. },
  571. ]
  572. }
  573. return [
  574. {
  575. id: Identifier.ascending("part"),
  576. ...part,
  577. messageID: userMsg.id,
  578. sessionID: input.sessionID,
  579. },
  580. ]
  581. }),
  582. ).then((x) => x.flat())
  583. await Plugin.trigger(
  584. "chat.message",
  585. {},
  586. {
  587. message: userMsg,
  588. parts: userParts,
  589. },
  590. )
  591. await updateMessage(userMsg)
  592. for (const part of userParts) {
  593. await updatePart(part)
  594. }
  595. // mark session as updated
  596. // used for session list sorting (indicates when session was most recently interacted with)
  597. await update(input.sessionID, (_draft) => {})
  598. if (isLocked(input.sessionID)) {
  599. return new Promise((resolve) => {
  600. const queue = state().queued.get(input.sessionID) ?? []
  601. queue.push({
  602. input: input,
  603. message: userMsg,
  604. parts: userParts,
  605. processed: false,
  606. callback: resolve,
  607. })
  608. state().queued.set(input.sessionID, queue)
  609. })
  610. }
  611. const model = await Provider.getModel(input.providerID, input.modelID)
  612. let msgs = await messages(input.sessionID)
  613. const previous = msgs.filter((x) => x.info.role === "assistant").at(-1)?.info as MessageV2.Assistant
  614. const outputLimit = Math.min(model.info.limit.output, OUTPUT_TOKEN_MAX) || OUTPUT_TOKEN_MAX
  615. // auto summarize if too long
  616. if (previous && previous.tokens) {
  617. const tokens =
  618. previous.tokens.input + previous.tokens.cache.read + previous.tokens.cache.write + previous.tokens.output
  619. if (model.info.limit.context && tokens > Math.max((model.info.limit.context - outputLimit) * 0.9, 0)) {
  620. state().autoCompacting.set(input.sessionID, true)
  621. await summarize({
  622. sessionID: input.sessionID,
  623. providerID: input.providerID,
  624. modelID: input.modelID,
  625. })
  626. return chat(input)
  627. }
  628. }
  629. using abort = lock(input.sessionID)
  630. const lastSummary = msgs.findLast((msg) => msg.info.role === "assistant" && msg.info.summary === true)
  631. if (lastSummary) msgs = msgs.filter((msg) => msg.info.id >= lastSummary.info.id)
  632. if (msgs.filter((m) => m.info.role === "user").length === 1 && !session.parentID && isDefaultTitle(session.title)) {
  633. const small = (await Provider.getSmallModel(input.providerID)) ?? model
  634. generateText({
  635. maxOutputTokens: small.info.reasoning ? 1024 : 20,
  636. providerOptions: {
  637. [input.providerID]: {
  638. ...small.info.options,
  639. ...ProviderTransform.options(input.providerID, small.info.id, input.sessionID),
  640. },
  641. },
  642. messages: [
  643. ...SystemPrompt.title(input.providerID).map(
  644. (x): ModelMessage => ({
  645. role: "system",
  646. content: x,
  647. }),
  648. ),
  649. ...MessageV2.toModelMessage([
  650. {
  651. info: {
  652. id: Identifier.ascending("message"),
  653. role: "user",
  654. sessionID: input.sessionID,
  655. time: {
  656. created: Date.now(),
  657. },
  658. },
  659. parts: userParts,
  660. },
  661. ]),
  662. ],
  663. model: small.language,
  664. })
  665. .then((result) => {
  666. if (result.text)
  667. return Session.update(input.sessionID, (draft) => {
  668. const cleaned = result.text.replace(/<think>[\s\S]*?<\/think>\s*/g, "")
  669. const title = cleaned.length > 100 ? cleaned.substring(0, 97) + "..." : cleaned
  670. draft.title = title.trim()
  671. })
  672. })
  673. .catch(() => {})
  674. }
  675. const agent = await Agent.get(inputAgent)
  676. if (agent.name === "plan") {
  677. msgs.at(-1)?.parts.push({
  678. id: Identifier.ascending("part"),
  679. messageID: userMsg.id,
  680. sessionID: input.sessionID,
  681. type: "text",
  682. text: PROMPT_PLAN,
  683. synthetic: true,
  684. })
  685. }
  686. const lastAssistantMsg = msgs.filter((x) => x.info.role === "assistant").at(-1)?.info as MessageV2.Assistant
  687. if (lastAssistantMsg?.mode === "plan" && agent.name === "build") {
  688. msgs.at(-1)?.parts.push({
  689. id: Identifier.ascending("part"),
  690. messageID: userMsg.id,
  691. sessionID: input.sessionID,
  692. type: "text",
  693. text: BUILD_SWITCH,
  694. synthetic: true,
  695. })
  696. }
  697. let system = SystemPrompt.header(input.providerID)
  698. system.push(
  699. ...(() => {
  700. if (input.system) return [input.system]
  701. if (agent.prompt) return [agent.prompt]
  702. return SystemPrompt.provider(input.modelID)
  703. })(),
  704. )
  705. system.push(...(await SystemPrompt.environment()))
  706. system.push(...(await SystemPrompt.custom()))
  707. // max 2 system prompt messages for caching purposes
  708. const [first, ...rest] = system
  709. system = [first, rest.join("\n")]
  710. const assistantMsg: MessageV2.Info = {
  711. id: Identifier.ascending("message"),
  712. role: "assistant",
  713. system,
  714. mode: inputAgent,
  715. path: {
  716. cwd: app.path.cwd,
  717. root: app.path.root,
  718. },
  719. cost: 0,
  720. tokens: {
  721. input: 0,
  722. output: 0,
  723. reasoning: 0,
  724. cache: { read: 0, write: 0 },
  725. },
  726. modelID: input.modelID,
  727. providerID: input.providerID,
  728. time: {
  729. created: Date.now(),
  730. },
  731. sessionID: input.sessionID,
  732. }
  733. await updateMessage(assistantMsg)
  734. await using _ = defer(async () => {
  735. if (assistantMsg.time.completed) return
  736. await Storage.remove(`session/message/${input.sessionID}/${assistantMsg.id}`)
  737. await Bus.publish(MessageV2.Event.Removed, { sessionID: input.sessionID, messageID: assistantMsg.id })
  738. })
  739. const tools: Record<string, AITool> = {}
  740. const processor = createProcessor(assistantMsg, model.info)
  741. const enabledTools = pipe(
  742. agent.tools,
  743. mergeDeep(await ToolRegistry.enabled(input.providerID, input.modelID, agent)),
  744. mergeDeep(input.tools ?? {}),
  745. )
  746. for (const item of await ToolRegistry.tools(input.providerID, input.modelID)) {
  747. if (Wildcard.all(item.id, enabledTools) === false) continue
  748. tools[item.id] = tool({
  749. id: item.id as any,
  750. description: item.description,
  751. inputSchema: item.parameters as ZodSchema,
  752. async execute(args, options) {
  753. await Plugin.trigger(
  754. "tool.execute.before",
  755. {
  756. tool: item.id,
  757. sessionID: input.sessionID,
  758. callID: options.toolCallId,
  759. },
  760. {
  761. args,
  762. },
  763. )
  764. const result = await item.execute(args, {
  765. sessionID: input.sessionID,
  766. abort: options.abortSignal!,
  767. messageID: assistantMsg.id,
  768. callID: options.toolCallId,
  769. agent: agent.name,
  770. metadata: async (val) => {
  771. const match = processor.partFromToolCall(options.toolCallId)
  772. if (match && match.state.status === "running") {
  773. await updatePart({
  774. ...match,
  775. state: {
  776. title: val.title,
  777. metadata: val.metadata,
  778. status: "running",
  779. input: args,
  780. time: {
  781. start: Date.now(),
  782. },
  783. },
  784. })
  785. }
  786. },
  787. })
  788. await Plugin.trigger(
  789. "tool.execute.after",
  790. {
  791. tool: item.id,
  792. sessionID: input.sessionID,
  793. callID: options.toolCallId,
  794. },
  795. result,
  796. )
  797. return result
  798. },
  799. toModelOutput(result) {
  800. return {
  801. type: "text",
  802. value: result.output,
  803. }
  804. },
  805. })
  806. }
  807. for (const [key, item] of Object.entries(await MCP.tools())) {
  808. if (Wildcard.all(key, enabledTools) === false) continue
  809. const execute = item.execute
  810. if (!execute) continue
  811. item.execute = async (args, opts) => {
  812. const result = await execute(args, opts)
  813. const output = result.content
  814. .filter((x: any) => x.type === "text")
  815. .map((x: any) => x.text)
  816. .join("\n\n")
  817. return {
  818. output,
  819. }
  820. }
  821. item.toModelOutput = (result) => {
  822. return {
  823. type: "text",
  824. value: result.output,
  825. }
  826. }
  827. tools[key] = item
  828. }
  829. const params = await Plugin.trigger(
  830. "chat.params",
  831. {
  832. model: model.info,
  833. provider: await Provider.getProvider(input.providerID),
  834. message: userMsg,
  835. },
  836. {
  837. temperature: model.info.temperature
  838. ? (agent.temperature ?? ProviderTransform.temperature(input.providerID, input.modelID))
  839. : undefined,
  840. topP: agent.topP ?? ProviderTransform.topP(input.providerID, input.modelID),
  841. options: {
  842. ...ProviderTransform.options(input.providerID, input.modelID, input.sessionID),
  843. ...model.info.options,
  844. ...agent.options,
  845. },
  846. },
  847. )
  848. const stream = streamText({
  849. onError(e) {
  850. log.error("streamText error", {
  851. error: e,
  852. })
  853. },
  854. async prepareStep({ messages }) {
  855. const queue = (state().queued.get(input.sessionID) ?? []).filter((x) => !x.processed)
  856. if (queue.length) {
  857. for (const item of queue) {
  858. if (item.processed) continue
  859. messages.push(
  860. ...MessageV2.toModelMessage([
  861. {
  862. info: item.message,
  863. parts: item.parts,
  864. },
  865. ]),
  866. )
  867. item.processed = true
  868. }
  869. assistantMsg.time.completed = Date.now()
  870. await updateMessage(assistantMsg)
  871. Object.assign(assistantMsg, {
  872. id: Identifier.ascending("message"),
  873. role: "assistant",
  874. system,
  875. path: {
  876. cwd: app.path.cwd,
  877. root: app.path.root,
  878. },
  879. cost: 0,
  880. tokens: {
  881. input: 0,
  882. output: 0,
  883. reasoning: 0,
  884. cache: { read: 0, write: 0 },
  885. },
  886. modelID: input.modelID,
  887. providerID: input.providerID,
  888. mode: inputAgent,
  889. time: {
  890. created: Date.now(),
  891. },
  892. sessionID: input.sessionID,
  893. })
  894. await updateMessage(assistantMsg)
  895. }
  896. return {
  897. messages,
  898. }
  899. },
  900. async experimental_repairToolCall(input) {
  901. return {
  902. ...input.toolCall,
  903. input: JSON.stringify({
  904. tool: input.toolCall.toolName,
  905. error: input.error.message,
  906. }),
  907. toolName: "invalid",
  908. }
  909. },
  910. headers:
  911. input.providerID === "opencode"
  912. ? {
  913. "x-opencode-session": input.sessionID,
  914. "x-opencode-request": userMsg.id,
  915. }
  916. : undefined,
  917. maxRetries: 3,
  918. activeTools: Object.keys(tools).filter((x) => x !== "invalid"),
  919. maxOutputTokens: outputLimit,
  920. abortSignal: abort.signal,
  921. stopWhen: async ({ steps }) => {
  922. if (steps.length >= 1000) {
  923. return true
  924. }
  925. // Check if processor flagged that we should stop
  926. if (processor.getShouldStop()) {
  927. return true
  928. }
  929. return false
  930. },
  931. providerOptions: {
  932. [input.providerID]: params.options,
  933. },
  934. temperature: params.temperature,
  935. topP: params.topP,
  936. messages: [
  937. ...system.map(
  938. (x): ModelMessage => ({
  939. role: "system",
  940. content: x,
  941. }),
  942. ),
  943. ...MessageV2.toModelMessage(msgs.filter((m) => !(m.info.role === "assistant" && m.info.error))),
  944. ],
  945. tools: model.info.tool_call === false ? undefined : tools,
  946. model: wrapLanguageModel({
  947. model: model.language,
  948. middleware: [
  949. {
  950. async transformParams(args) {
  951. if (args.type === "stream") {
  952. // @ts-expect-error
  953. args.params.prompt = ProviderTransform.message(args.params.prompt, input.providerID, input.modelID)
  954. }
  955. return args.params
  956. },
  957. },
  958. ],
  959. }),
  960. })
  961. const result = await processor.process(stream)
  962. const queued = state().queued.get(input.sessionID) ?? []
  963. const unprocessed = queued.find((x) => !x.processed)
  964. if (unprocessed) {
  965. unprocessed.processed = true
  966. return chat(unprocessed.input)
  967. }
  968. for (const item of queued) {
  969. item.callback(result)
  970. }
  971. state().queued.delete(input.sessionID)
  972. return result
  973. }
  974. export const ShellInput = z.object({
  975. sessionID: Identifier.schema("session"),
  976. agent: z.string(),
  977. command: z.string(),
  978. })
  979. export type ShellInput = z.infer<typeof ShellInput>
  980. export async function shell(input: ShellInput) {
  981. using abort = lock(input.sessionID)
  982. const msg: MessageV2.Assistant = {
  983. id: Identifier.ascending("message"),
  984. sessionID: input.sessionID,
  985. system: [],
  986. mode: input.agent,
  987. cost: 0,
  988. path: {
  989. cwd: App.info().path.cwd,
  990. root: App.info().path.root,
  991. },
  992. time: {
  993. created: Date.now(),
  994. },
  995. role: "assistant",
  996. tokens: {
  997. input: 0,
  998. output: 0,
  999. reasoning: 0,
  1000. cache: { read: 0, write: 0 },
  1001. },
  1002. modelID: "",
  1003. providerID: "",
  1004. }
  1005. await updateMessage(msg)
  1006. const part: MessageV2.Part = {
  1007. type: "tool",
  1008. id: Identifier.ascending("part"),
  1009. messageID: msg.id,
  1010. sessionID: input.sessionID,
  1011. tool: "bash",
  1012. callID: ulid(),
  1013. state: {
  1014. status: "running",
  1015. time: {
  1016. start: Date.now(),
  1017. },
  1018. input: {
  1019. command: input.command,
  1020. },
  1021. },
  1022. }
  1023. await updatePart(part)
  1024. const app = App.info()
  1025. const shell = process.env["SHELL"] ?? "bash"
  1026. const shellName = path.basename(shell)
  1027. const scripts: Record<string, string> = {
  1028. nu: input.command,
  1029. fish: `eval "${input.command}"`,
  1030. }
  1031. const script =
  1032. scripts[shellName] ??
  1033. `[[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
  1034. [[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
  1035. [[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
  1036. eval "${input.command}"`
  1037. const isFishOrNu = shellName === "fish" || shellName === "nu"
  1038. const args = isFishOrNu ? ["-c", script] : ["-c", "-l", script]
  1039. const proc = spawn(shell, args, {
  1040. cwd: app.path.cwd,
  1041. signal: abort.signal,
  1042. stdio: ["ignore", "pipe", "pipe"],
  1043. env: {
  1044. ...process.env,
  1045. TERM: "dumb",
  1046. },
  1047. })
  1048. let output = ""
  1049. proc.stdout?.on("data", (chunk) => {
  1050. output += chunk.toString()
  1051. if (part.state.status === "running") {
  1052. part.state.metadata = {
  1053. output: output,
  1054. description: "",
  1055. }
  1056. updatePart(part)
  1057. }
  1058. })
  1059. proc.stderr?.on("data", (chunk) => {
  1060. output += chunk.toString()
  1061. if (part.state.status === "running") {
  1062. part.state.metadata = {
  1063. output: output,
  1064. description: "",
  1065. }
  1066. updatePart(part)
  1067. }
  1068. })
  1069. await new Promise<void>((resolve) => {
  1070. proc.on("close", () => {
  1071. resolve()
  1072. })
  1073. })
  1074. msg.time.completed = Date.now()
  1075. await updateMessage(msg)
  1076. if (part.state.status === "running") {
  1077. part.state = {
  1078. status: "completed",
  1079. time: {
  1080. ...part.state.time,
  1081. end: Date.now(),
  1082. },
  1083. input: part.state.input,
  1084. title: "",
  1085. metadata: {
  1086. output,
  1087. description: "",
  1088. },
  1089. output,
  1090. }
  1091. await updatePart(part)
  1092. }
  1093. return { info: msg, parts: [part] }
  1094. }
  1095. export const CommandInput = z.object({
  1096. messageID: Identifier.schema("message").optional(),
  1097. sessionID: Identifier.schema("session"),
  1098. agent: z.string().optional(),
  1099. model: z.string().optional(),
  1100. arguments: z.string(),
  1101. command: z.string(),
  1102. })
  1103. export type CommandInput = z.infer<typeof CommandInput>
  1104. const bashRegex = /!`([^`]+)`/g
  1105. const fileRegex = /@([^\s]+)/g
  1106. export async function command(input: CommandInput) {
  1107. const command = await Command.get(input.command)
  1108. const agent = input.agent ?? command.agent ?? "build"
  1109. const model =
  1110. input.model ??
  1111. command.model ??
  1112. (await Agent.get(agent).then((x) => (x.model ? `${x.model.providerID}/${x.model.modelID}` : undefined))) ??
  1113. (await Provider.defaultModel().then((x) => `${x.providerID}/${x.modelID}`))
  1114. let template = command.template.replace("$ARGUMENTS", input.arguments)
  1115. const bash = Array.from(template.matchAll(bashRegex))
  1116. if (bash.length > 0) {
  1117. const results = await Promise.all(
  1118. bash.map(async ([, cmd]) => {
  1119. try {
  1120. return await $`${{ raw: cmd }}`.nothrow().text()
  1121. } catch (error) {
  1122. return `Error executing command: ${error instanceof Error ? error.message : String(error)}`
  1123. }
  1124. }),
  1125. )
  1126. let index = 0
  1127. template = template.replace(bashRegex, () => results[index++])
  1128. }
  1129. const parts = [
  1130. {
  1131. type: "text",
  1132. text: template,
  1133. },
  1134. ] as ChatInput["parts"]
  1135. const matches = template.matchAll(fileRegex)
  1136. const app = App.info()
  1137. for (const match of matches) {
  1138. const file = path.join(app.path.cwd, match[1])
  1139. parts.push({
  1140. type: "file",
  1141. url: `file://${file}`,
  1142. filename: match[1],
  1143. mime: "text/plain",
  1144. })
  1145. }
  1146. return chat({
  1147. sessionID: input.sessionID,
  1148. messageID: input.messageID,
  1149. ...Provider.parseModel(model!),
  1150. agent,
  1151. parts,
  1152. })
  1153. }
  1154. function createProcessor(assistantMsg: MessageV2.Assistant, model: ModelsDev.Model) {
  1155. const toolcalls: Record<string, MessageV2.ToolPart> = {}
  1156. let snapshot: string | undefined
  1157. let shouldStop = false
  1158. return {
  1159. partFromToolCall(toolCallID: string) {
  1160. return toolcalls[toolCallID]
  1161. },
  1162. getShouldStop() {
  1163. return shouldStop
  1164. },
  1165. async process(stream: StreamTextResult<Record<string, AITool>, never>) {
  1166. try {
  1167. let currentText: MessageV2.TextPart | undefined
  1168. let reasoningMap: Record<string, MessageV2.ReasoningPart> = {}
  1169. for await (const value of stream.fullStream) {
  1170. log.info("part", {
  1171. type: value.type,
  1172. })
  1173. switch (value.type) {
  1174. case "start":
  1175. break
  1176. case "reasoning-start":
  1177. if (value.id in reasoningMap) {
  1178. continue
  1179. }
  1180. reasoningMap[value.id] = {
  1181. id: Identifier.ascending("part"),
  1182. messageID: assistantMsg.id,
  1183. sessionID: assistantMsg.sessionID,
  1184. type: "reasoning",
  1185. text: "",
  1186. time: {
  1187. start: Date.now(),
  1188. },
  1189. }
  1190. break
  1191. case "reasoning-delta":
  1192. if (value.id in reasoningMap) {
  1193. const part = reasoningMap[value.id]
  1194. part.text += value.text
  1195. if (part.text) await updatePart(part)
  1196. }
  1197. break
  1198. case "reasoning-end":
  1199. if (value.id in reasoningMap) {
  1200. const part = reasoningMap[value.id]
  1201. part.text = part.text.trimEnd()
  1202. part.metadata = value.providerMetadata
  1203. part.time = {
  1204. ...part.time,
  1205. end: Date.now(),
  1206. }
  1207. await updatePart(part)
  1208. delete reasoningMap[value.id]
  1209. }
  1210. break
  1211. case "tool-input-start":
  1212. const part = await updatePart({
  1213. id: toolcalls[value.id]?.id ?? Identifier.ascending("part"),
  1214. messageID: assistantMsg.id,
  1215. sessionID: assistantMsg.sessionID,
  1216. type: "tool",
  1217. tool: value.toolName,
  1218. callID: value.id,
  1219. state: {
  1220. status: "pending",
  1221. },
  1222. })
  1223. toolcalls[value.id] = part as MessageV2.ToolPart
  1224. break
  1225. case "tool-input-delta":
  1226. break
  1227. case "tool-input-end":
  1228. break
  1229. case "tool-call": {
  1230. const match = toolcalls[value.toolCallId]
  1231. if (match) {
  1232. const part = await updatePart({
  1233. ...match,
  1234. tool: value.toolName,
  1235. state: {
  1236. status: "running",
  1237. input: value.input,
  1238. time: {
  1239. start: Date.now(),
  1240. },
  1241. },
  1242. })
  1243. toolcalls[value.toolCallId] = part as MessageV2.ToolPart
  1244. }
  1245. break
  1246. }
  1247. case "tool-result": {
  1248. const match = toolcalls[value.toolCallId]
  1249. if (match && match.state.status === "running") {
  1250. await updatePart({
  1251. ...match,
  1252. state: {
  1253. status: "completed",
  1254. input: value.input,
  1255. output: value.output.output,
  1256. metadata: value.output.metadata,
  1257. title: value.output.title,
  1258. time: {
  1259. start: match.state.time.start,
  1260. end: Date.now(),
  1261. },
  1262. },
  1263. })
  1264. delete toolcalls[value.toolCallId]
  1265. }
  1266. break
  1267. }
  1268. case "tool-error": {
  1269. const match = toolcalls[value.toolCallId]
  1270. if (match && match.state.status === "running") {
  1271. if (value.error instanceof Permission.RejectedError) {
  1272. shouldStop = true
  1273. }
  1274. await updatePart({
  1275. ...match,
  1276. state: {
  1277. status: "error",
  1278. input: value.input,
  1279. error: (value.error as any).toString(),
  1280. metadata: value.error instanceof Permission.RejectedError ? value.error.metadata : undefined,
  1281. time: {
  1282. start: match.state.time.start,
  1283. end: Date.now(),
  1284. },
  1285. },
  1286. })
  1287. delete toolcalls[value.toolCallId]
  1288. }
  1289. break
  1290. }
  1291. case "error":
  1292. throw value.error
  1293. case "start-step":
  1294. await updatePart({
  1295. id: Identifier.ascending("part"),
  1296. messageID: assistantMsg.id,
  1297. sessionID: assistantMsg.sessionID,
  1298. type: "step-start",
  1299. })
  1300. snapshot = await Snapshot.track()
  1301. break
  1302. case "finish-step":
  1303. const usage = getUsage(model, value.usage, value.providerMetadata)
  1304. assistantMsg.cost += usage.cost
  1305. assistantMsg.tokens = usage.tokens
  1306. await updatePart({
  1307. id: Identifier.ascending("part"),
  1308. messageID: assistantMsg.id,
  1309. sessionID: assistantMsg.sessionID,
  1310. type: "step-finish",
  1311. tokens: usage.tokens,
  1312. cost: usage.cost,
  1313. })
  1314. await updateMessage(assistantMsg)
  1315. if (snapshot) {
  1316. const patch = await Snapshot.patch(snapshot)
  1317. if (patch.files.length) {
  1318. await updatePart({
  1319. id: Identifier.ascending("part"),
  1320. messageID: assistantMsg.id,
  1321. sessionID: assistantMsg.sessionID,
  1322. type: "patch",
  1323. hash: patch.hash,
  1324. files: patch.files,
  1325. })
  1326. }
  1327. snapshot = undefined
  1328. }
  1329. break
  1330. case "text-start":
  1331. currentText = {
  1332. id: Identifier.ascending("part"),
  1333. messageID: assistantMsg.id,
  1334. sessionID: assistantMsg.sessionID,
  1335. type: "text",
  1336. text: "",
  1337. time: {
  1338. start: Date.now(),
  1339. },
  1340. }
  1341. break
  1342. case "text-delta":
  1343. if (currentText) {
  1344. currentText.text += value.text
  1345. if (currentText.text) await updatePart(currentText)
  1346. }
  1347. break
  1348. case "text-end":
  1349. if (currentText) {
  1350. currentText.text = currentText.text.trimEnd()
  1351. currentText.time = {
  1352. start: Date.now(),
  1353. end: Date.now(),
  1354. }
  1355. await updatePart(currentText)
  1356. }
  1357. currentText = undefined
  1358. break
  1359. case "finish":
  1360. assistantMsg.time.completed = Date.now()
  1361. await updateMessage(assistantMsg)
  1362. break
  1363. default:
  1364. log.info("unhandled", {
  1365. ...value,
  1366. })
  1367. continue
  1368. }
  1369. }
  1370. } catch (e) {
  1371. log.error("", {
  1372. error: e,
  1373. })
  1374. switch (true) {
  1375. case e instanceof DOMException && e.name === "AbortError":
  1376. assistantMsg.error = new MessageV2.AbortedError(
  1377. { message: e.message },
  1378. {
  1379. cause: e,
  1380. },
  1381. ).toObject()
  1382. break
  1383. case MessageV2.OutputLengthError.isInstance(e):
  1384. assistantMsg.error = e
  1385. break
  1386. case LoadAPIKeyError.isInstance(e):
  1387. assistantMsg.error = new MessageV2.AuthError(
  1388. {
  1389. providerID: model.id,
  1390. message: e.message,
  1391. },
  1392. { cause: e },
  1393. ).toObject()
  1394. break
  1395. case e instanceof Error:
  1396. assistantMsg.error = new NamedError.Unknown({ message: e.toString() }, { cause: e }).toObject()
  1397. break
  1398. default:
  1399. assistantMsg.error = new NamedError.Unknown({ message: JSON.stringify(e) }, { cause: e })
  1400. }
  1401. Bus.publish(Event.Error, {
  1402. sessionID: assistantMsg.sessionID,
  1403. error: assistantMsg.error,
  1404. })
  1405. }
  1406. const p = await getParts(assistantMsg.sessionID, assistantMsg.id)
  1407. for (const part of p) {
  1408. if (part.type === "tool" && part.state.status !== "completed" && part.state.status !== "error") {
  1409. updatePart({
  1410. ...part,
  1411. state: {
  1412. status: "error",
  1413. error: "Tool execution aborted",
  1414. time: {
  1415. start: Date.now(),
  1416. end: Date.now(),
  1417. },
  1418. input: {},
  1419. },
  1420. })
  1421. }
  1422. }
  1423. assistantMsg.time.completed = Date.now()
  1424. await updateMessage(assistantMsg)
  1425. return { info: assistantMsg, parts: p }
  1426. },
  1427. }
  1428. }
  1429. export const RevertInput = z.object({
  1430. sessionID: Identifier.schema("session"),
  1431. messageID: Identifier.schema("message"),
  1432. partID: Identifier.schema("part").optional(),
  1433. })
  1434. export type RevertInput = z.infer<typeof RevertInput>
  1435. export async function revert(input: RevertInput) {
  1436. const all = await messages(input.sessionID)
  1437. let lastUser: MessageV2.User | undefined
  1438. const session = await get(input.sessionID)
  1439. let revert: Info["revert"]
  1440. const patches: Snapshot.Patch[] = []
  1441. for (const msg of all) {
  1442. if (msg.info.role === "user") lastUser = msg.info
  1443. const remaining = []
  1444. for (const part of msg.parts) {
  1445. if (revert) {
  1446. if (part.type === "patch") {
  1447. patches.push(part)
  1448. }
  1449. continue
  1450. }
  1451. if (!revert) {
  1452. if ((msg.info.id === input.messageID && !input.partID) || part.id === input.partID) {
  1453. // if no useful parts left in message, same as reverting whole message
  1454. const partID = remaining.some((item) => ["text", "tool"].includes(item.type)) ? input.partID : undefined
  1455. revert = {
  1456. messageID: !partID && lastUser ? lastUser.id : msg.info.id,
  1457. partID,
  1458. }
  1459. }
  1460. remaining.push(part)
  1461. }
  1462. }
  1463. }
  1464. if (revert) {
  1465. const session = await get(input.sessionID)
  1466. revert.snapshot = session.revert?.snapshot ?? (await Snapshot.track())
  1467. await Snapshot.revert(patches)
  1468. if (revert.snapshot) revert.diff = await Snapshot.diff(revert.snapshot)
  1469. return update(input.sessionID, (draft) => {
  1470. draft.revert = revert
  1471. })
  1472. }
  1473. return session
  1474. }
  1475. export async function unrevert(input: { sessionID: string }) {
  1476. log.info("unreverting", input)
  1477. const session = await get(input.sessionID)
  1478. if (!session.revert) return session
  1479. if (session.revert.snapshot) await Snapshot.restore(session.revert.snapshot)
  1480. const next = await update(input.sessionID, (draft) => {
  1481. draft.revert = undefined
  1482. })
  1483. return next
  1484. }
  1485. export async function summarize(input: { sessionID: string; providerID: string; modelID: string }) {
  1486. using abort = lock(input.sessionID)
  1487. const msgs = await messages(input.sessionID)
  1488. const lastSummary = msgs.findLast((msg) => msg.info.role === "assistant" && msg.info.summary === true)
  1489. const filtered = msgs.filter((msg) => !lastSummary || msg.info.id >= lastSummary.info.id)
  1490. const model = await Provider.getModel(input.providerID, input.modelID)
  1491. const app = App.info()
  1492. const system = [
  1493. ...SystemPrompt.summarize(input.providerID),
  1494. ...(await SystemPrompt.environment()),
  1495. ...(await SystemPrompt.custom()),
  1496. ]
  1497. const next: MessageV2.Info = {
  1498. id: Identifier.ascending("message"),
  1499. role: "assistant",
  1500. sessionID: input.sessionID,
  1501. system,
  1502. mode: "build",
  1503. path: {
  1504. cwd: app.path.cwd,
  1505. root: app.path.root,
  1506. },
  1507. summary: true,
  1508. cost: 0,
  1509. modelID: input.modelID,
  1510. providerID: input.providerID,
  1511. tokens: {
  1512. input: 0,
  1513. output: 0,
  1514. reasoning: 0,
  1515. cache: { read: 0, write: 0 },
  1516. },
  1517. time: {
  1518. created: Date.now(),
  1519. },
  1520. }
  1521. await updateMessage(next)
  1522. const processor = createProcessor(next, model.info)
  1523. const stream = streamText({
  1524. maxRetries: 10,
  1525. abortSignal: abort.signal,
  1526. model: model.language,
  1527. messages: [
  1528. ...system.map(
  1529. (x): ModelMessage => ({
  1530. role: "system",
  1531. content: x,
  1532. }),
  1533. ),
  1534. ...MessageV2.toModelMessage(filtered),
  1535. {
  1536. role: "user",
  1537. content: [
  1538. {
  1539. type: "text",
  1540. text: "Provide a detailed but concise summary of our conversation above. Focus on information that would be helpful for continuing the conversation, including what we did, what we're doing, which files we're working on, and what we're going to do next.",
  1541. },
  1542. ],
  1543. },
  1544. ],
  1545. })
  1546. const result = await processor.process(stream)
  1547. return result
  1548. }
  1549. function isLocked(sessionID: string) {
  1550. return state().pending.has(sessionID)
  1551. }
  1552. function lock(sessionID: string) {
  1553. log.info("locking", { sessionID })
  1554. if (state().pending.has(sessionID)) throw new BusyError(sessionID)
  1555. const controller = new AbortController()
  1556. state().pending.set(sessionID, controller)
  1557. return {
  1558. signal: controller.signal,
  1559. async [Symbol.dispose]() {
  1560. log.info("unlocking", { sessionID })
  1561. state().pending.delete(sessionID)
  1562. const isAutoCompacting = state().autoCompacting.get(sessionID) ?? false
  1563. if (isAutoCompacting) {
  1564. state().autoCompacting.delete(sessionID)
  1565. return
  1566. }
  1567. const session = await get(sessionID)
  1568. if (session.parentID) return
  1569. Bus.publish(Event.Idle, {
  1570. sessionID,
  1571. })
  1572. },
  1573. }
  1574. }
  1575. function getUsage(model: ModelsDev.Model, usage: LanguageModelUsage, metadata?: ProviderMetadata) {
  1576. const tokens = {
  1577. input: usage.inputTokens ?? 0,
  1578. output: usage.outputTokens ?? 0,
  1579. reasoning: usage?.reasoningTokens ?? 0,
  1580. cache: {
  1581. write: (metadata?.["anthropic"]?.["cacheCreationInputTokens"] ??
  1582. // @ts-expect-error
  1583. metadata?.["bedrock"]?.["usage"]?.["cacheWriteInputTokens"] ??
  1584. 0) as number,
  1585. read: usage.cachedInputTokens ?? 0,
  1586. },
  1587. }
  1588. return {
  1589. cost: new Decimal(0)
  1590. .add(new Decimal(tokens.input).mul(model.cost?.input ?? 0).div(1_000_000))
  1591. .add(new Decimal(tokens.output).mul(model.cost?.output ?? 0).div(1_000_000))
  1592. .add(new Decimal(tokens.cache.read).mul(model.cost?.cache_read ?? 0).div(1_000_000))
  1593. .add(new Decimal(tokens.cache.write).mul(model.cost?.cache_write ?? 0).div(1_000_000))
  1594. .toNumber(),
  1595. tokens,
  1596. }
  1597. }
  1598. export class BusyError extends Error {
  1599. constructor(public readonly sessionID: string) {
  1600. super(`Session ${sessionID} is busy`)
  1601. }
  1602. }
  1603. export async function initialize(input: {
  1604. sessionID: string
  1605. modelID: string
  1606. providerID: string
  1607. messageID: string
  1608. }) {
  1609. const app = App.info()
  1610. await Session.chat({
  1611. sessionID: input.sessionID,
  1612. messageID: input.messageID,
  1613. providerID: input.providerID,
  1614. modelID: input.modelID,
  1615. parts: [
  1616. {
  1617. id: Identifier.ascending("part"),
  1618. type: "text",
  1619. text: PROMPT_INITIALIZE.replace("${path}", app.path.root),
  1620. },
  1621. ],
  1622. })
  1623. await App.initialize()
  1624. }
  1625. }