index.ts 46 KB

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