index.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. import path from "path"
  2. import { App } from "../app/app"
  3. import { Identifier } from "../id/id"
  4. import { Storage } from "../storage/storage"
  5. import { Log } from "../util/log"
  6. import {
  7. convertToModelMessages,
  8. generateText,
  9. stepCountIs,
  10. streamText,
  11. tool,
  12. type Tool as AITool,
  13. type LanguageModelUsage,
  14. } from "ai"
  15. import { z, ZodSchema } from "zod"
  16. import { Decimal } from "decimal.js"
  17. import PROMPT_ANTHROPIC from "./prompt/anthropic.txt"
  18. import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt"
  19. import PROMPT_TITLE from "./prompt/title.txt"
  20. import PROMPT_SUMMARIZE from "./prompt/summarize.txt"
  21. import PROMPT_INITIALIZE from "../session/prompt/initialize.txt"
  22. import { Share } from "../share/share"
  23. import { Message } from "./message"
  24. import { Bus } from "../bus"
  25. import { Provider } from "../provider/provider"
  26. import { SessionContext } from "./context"
  27. import { ListTool } from "../tool/ls"
  28. import { MCP } from "../mcp"
  29. export namespace Session {
  30. const log = Log.create({ service: "session" })
  31. export const Info = z
  32. .object({
  33. id: Identifier.schema("session"),
  34. share: z
  35. .object({
  36. secret: z.string(),
  37. url: z.string(),
  38. })
  39. .optional(),
  40. title: z.string(),
  41. time: z.object({
  42. created: z.number(),
  43. updated: z.number(),
  44. }),
  45. })
  46. .openapi({
  47. ref: "session.info",
  48. })
  49. export type Info = z.output<typeof Info>
  50. export const Event = {
  51. Updated: Bus.event(
  52. "session.updated",
  53. z.object({
  54. info: Info,
  55. }),
  56. ),
  57. }
  58. const state = App.state("session", () => {
  59. const sessions = new Map<string, Info>()
  60. const messages = new Map<string, Message.Info[]>()
  61. return {
  62. sessions,
  63. messages,
  64. }
  65. })
  66. export async function create() {
  67. const result: Info = {
  68. id: Identifier.descending("session"),
  69. title: "New Session - " + new Date().toISOString(),
  70. time: {
  71. created: Date.now(),
  72. updated: Date.now(),
  73. },
  74. }
  75. log.info("created", result)
  76. state().sessions.set(result.id, result)
  77. await Storage.writeJSON("session/info/" + result.id, result)
  78. share(result.id).then((share) => {
  79. update(result.id, (draft) => {
  80. draft.share = share
  81. })
  82. })
  83. Bus.publish(Event.Updated, {
  84. info: result,
  85. })
  86. return result
  87. }
  88. export async function get(id: string) {
  89. const result = state().sessions.get(id)
  90. if (result) {
  91. return result
  92. }
  93. const read = await Storage.readJSON<Info>("session/info/" + id)
  94. state().sessions.set(id, read)
  95. return read as Info
  96. }
  97. export async function share(id: string) {
  98. const session = await get(id)
  99. if (session.share) return session.share
  100. const share = await Share.create(id)
  101. await update(id, (draft) => {
  102. draft.share = share
  103. })
  104. for (const msg of await messages(id)) {
  105. await Share.sync("session/message/" + id + "/" + msg.id, msg)
  106. }
  107. return share
  108. }
  109. export async function update(id: string, editor: (session: Info) => void) {
  110. const { sessions } = state()
  111. const session = await get(id)
  112. if (!session) return
  113. editor(session)
  114. session.time.updated = Date.now()
  115. sessions.set(id, session)
  116. await Storage.writeJSON("session/info/" + id, session)
  117. Bus.publish(Event.Updated, {
  118. info: session,
  119. })
  120. return session
  121. }
  122. export async function messages(sessionID: string) {
  123. const result = [] as Message.Info[]
  124. const list = Storage.list("session/message/" + sessionID)
  125. for await (const p of list) {
  126. const read = await Storage.readJSON<Message.Info>(p).catch(() => {})
  127. if (!read) continue
  128. result.push(read)
  129. }
  130. result.sort((a, b) => (a.id > b.id ? 1 : -1))
  131. return result
  132. }
  133. export async function* list() {
  134. for await (const item of Storage.list("session/info")) {
  135. const sessionID = path.basename(item, ".json")
  136. yield get(sessionID)
  137. }
  138. }
  139. export function abort(sessionID: string) {
  140. const controller = pending.get(sessionID)
  141. if (!controller) return false
  142. controller.abort()
  143. pending.delete(sessionID)
  144. return true
  145. }
  146. async function updateMessage(msg: Message.Info) {
  147. await Storage.writeJSON(
  148. "session/message/" + msg.metadata.sessionID + "/" + msg.id,
  149. msg,
  150. )
  151. Bus.publish(Message.Event.Updated, {
  152. info: msg,
  153. })
  154. }
  155. export async function chat(input: {
  156. sessionID: string
  157. providerID: string
  158. modelID: string
  159. parts: Message.Part[]
  160. }) {
  161. const l = log.clone().tag("session", input.sessionID)
  162. l.info("chatting")
  163. const model = await Provider.getModel(input.providerID, input.modelID)
  164. let msgs = await messages(input.sessionID)
  165. const previous = msgs.at(-1)
  166. if (previous?.metadata.assistant) {
  167. const tokens =
  168. previous.metadata.assistant.tokens.input +
  169. previous.metadata.assistant.tokens.output
  170. if (
  171. tokens >
  172. (model.info.contextWindow - (model.info.maxOutputTokens ?? 0)) * 0.9
  173. ) {
  174. await summarize({
  175. sessionID: input.sessionID,
  176. providerID: input.providerID,
  177. modelID: input.modelID,
  178. })
  179. return chat(input)
  180. }
  181. }
  182. using abort = lock(input.sessionID)
  183. const lastSummary = msgs.findLast(
  184. (msg) => msg.metadata.assistant?.summary === true,
  185. )
  186. if (lastSummary)
  187. msgs = msgs.filter(
  188. (msg) => msg.role === "system" || msg.id >= lastSummary.id,
  189. )
  190. if (msgs.length === 0) {
  191. const app = App.info()
  192. if (input.providerID === "anthropic") {
  193. const claude: Message.Info = {
  194. id: Identifier.ascending("message"),
  195. role: "system",
  196. parts: [
  197. {
  198. type: "text",
  199. text: PROMPT_ANTHROPIC_SPOOF.trim(),
  200. },
  201. ],
  202. metadata: {
  203. sessionID: input.sessionID,
  204. time: {
  205. created: Date.now(),
  206. },
  207. tool: {},
  208. },
  209. }
  210. await updateMessage(claude)
  211. msgs.push(claude)
  212. }
  213. const system: Message.Info = {
  214. id: Identifier.ascending("message"),
  215. role: "system",
  216. parts: [
  217. {
  218. type: "text",
  219. text: PROMPT_ANTHROPIC,
  220. },
  221. {
  222. type: "text",
  223. text: [
  224. `Here is some useful information about the environment you are running in:`,
  225. `<env>`,
  226. `Working directory: ${app.path.cwd}`,
  227. `Is directory a git repo: ${app.git ? "yes" : "no"}`,
  228. `Platform: ${process.platform}`,
  229. `Today's date: ${new Date().toISOString()}`,
  230. `</env>`,
  231. `<project>`,
  232. `${app.git ? await ListTool.execute({ path: app.path.cwd }, { sessionID: input.sessionID }).then((x) => x.output) : ""}`,
  233. `</project>`,
  234. ].join("\n"),
  235. },
  236. ],
  237. metadata: {
  238. sessionID: input.sessionID,
  239. time: {
  240. created: Date.now(),
  241. },
  242. tool: {},
  243. },
  244. }
  245. const context = await SessionContext.find()
  246. if (context) {
  247. system.parts.push({
  248. type: "text",
  249. text: context,
  250. })
  251. }
  252. msgs.push(system)
  253. generateText({
  254. maxOutputTokens: 80,
  255. messages: convertToModelMessages([
  256. {
  257. role: "system",
  258. parts: [
  259. {
  260. type: "text",
  261. text: PROMPT_ANTHROPIC_SPOOF.trim(),
  262. },
  263. ],
  264. },
  265. {
  266. role: "system",
  267. parts: [
  268. {
  269. type: "text",
  270. text: PROMPT_TITLE,
  271. },
  272. ],
  273. },
  274. {
  275. role: "user",
  276. parts: input.parts,
  277. },
  278. ]),
  279. model: model.language,
  280. }).then((result) => {
  281. return Session.update(input.sessionID, (draft) => {
  282. draft.title = result.text
  283. })
  284. })
  285. await updateMessage(system)
  286. }
  287. const msg: Message.Info = {
  288. role: "user",
  289. id: Identifier.ascending("message"),
  290. parts: input.parts,
  291. metadata: {
  292. time: {
  293. created: Date.now(),
  294. },
  295. sessionID: input.sessionID,
  296. tool: {},
  297. },
  298. }
  299. await updateMessage(msg)
  300. msgs.push(msg)
  301. const next: Message.Info = {
  302. id: Identifier.ascending("message"),
  303. role: "assistant",
  304. parts: [],
  305. metadata: {
  306. assistant: {
  307. cost: 0,
  308. tokens: {
  309. input: 0,
  310. output: 0,
  311. reasoning: 0,
  312. },
  313. modelID: input.modelID,
  314. providerID: input.providerID,
  315. },
  316. time: {
  317. created: Date.now(),
  318. },
  319. sessionID: input.sessionID,
  320. tool: {},
  321. },
  322. }
  323. await updateMessage(next)
  324. const tools: Record<string, AITool> = {}
  325. for (const item of await Provider.tools(input.providerID)) {
  326. tools[item.id.replaceAll(".", "_")] = tool({
  327. id: item.id as any,
  328. description: item.description,
  329. parameters: item.parameters as ZodSchema,
  330. async execute(args, opts) {
  331. const start = Date.now()
  332. try {
  333. const result = await item.execute(args, {
  334. sessionID: input.sessionID,
  335. })
  336. next.metadata!.tool![opts.toolCallId] = {
  337. ...result.metadata,
  338. time: {
  339. start,
  340. end: Date.now(),
  341. },
  342. }
  343. return result.output
  344. } catch (e: any) {
  345. next.metadata!.tool![opts.toolCallId] = {
  346. error: true,
  347. message: e.toString(),
  348. time: {
  349. start,
  350. end: Date.now(),
  351. },
  352. }
  353. return e.toString()
  354. }
  355. },
  356. })
  357. }
  358. for (const [key, item] of Object.entries(await MCP.tools())) {
  359. const execute = item.execute
  360. if (!execute) continue
  361. item.execute = async (args, opts) => {
  362. const start = Date.now()
  363. try {
  364. const result = await execute(args, opts)
  365. next.metadata!.tool![opts.toolCallId] = {
  366. ...result.metadata,
  367. time: {
  368. start,
  369. end: Date.now(),
  370. },
  371. }
  372. return result.content
  373. .filter((x: any) => x.type === "text")
  374. .map((x: any) => x.text)
  375. .join("\n\n")
  376. } catch (e: any) {
  377. next.metadata!.tool![opts.toolCallId] = {
  378. error: true,
  379. message: e.toString(),
  380. time: {
  381. start,
  382. end: Date.now(),
  383. },
  384. }
  385. return e.toString()
  386. }
  387. }
  388. tools[key] = item
  389. }
  390. let text: Message.TextPart | undefined
  391. const result = streamText({
  392. onStepFinish: async (step) => {
  393. log.info("step finish", {
  394. finishReason: step.finishReason,
  395. })
  396. const assistant = next.metadata!.assistant!
  397. const usage = getUsage(step.usage, model.info)
  398. assistant.cost += usage.cost
  399. assistant.tokens = usage.tokens
  400. await updateMessage(next)
  401. if (text) {
  402. Bus.publish(Message.Event.PartUpdated, {
  403. part: text,
  404. })
  405. }
  406. text = undefined
  407. },
  408. async onChunk(input) {
  409. const value = input.chunk
  410. l.info("part", {
  411. type: value.type,
  412. })
  413. switch (value.type) {
  414. case "text":
  415. if (!text) {
  416. text = value
  417. next.parts.push(value)
  418. break
  419. } else text.text += value.text
  420. break
  421. case "tool-call":
  422. next.parts.push({
  423. type: "tool-invocation",
  424. toolInvocation: {
  425. state: "call",
  426. ...value,
  427. // hack until zod v4
  428. args: value.args as any,
  429. },
  430. })
  431. Bus.publish(Message.Event.PartUpdated, {
  432. part: next.parts[next.parts.length - 1],
  433. })
  434. break
  435. case "tool-call-streaming-start":
  436. next.parts.push({
  437. type: "tool-invocation",
  438. toolInvocation: {
  439. state: "partial-call",
  440. toolName: value.toolName,
  441. toolCallId: value.toolCallId,
  442. args: {},
  443. },
  444. })
  445. Bus.publish(Message.Event.PartUpdated, {
  446. part: next.parts[next.parts.length - 1],
  447. })
  448. break
  449. case "tool-call-delta":
  450. break
  451. case "tool-result":
  452. const match = next.parts.find(
  453. (p) =>
  454. p.type === "tool-invocation" &&
  455. p.toolInvocation.toolCallId === value.toolCallId,
  456. )
  457. if (match && match.type === "tool-invocation") {
  458. match.toolInvocation = {
  459. args: match.toolInvocation.args,
  460. toolCallId: match.toolInvocation.toolCallId,
  461. toolName: match.toolInvocation.toolName,
  462. state: "result",
  463. result: value.result as string,
  464. }
  465. Bus.publish(Message.Event.PartUpdated, {
  466. part: match,
  467. })
  468. }
  469. break
  470. default:
  471. l.info("unhandled", {
  472. type: value.type,
  473. })
  474. }
  475. await updateMessage(next)
  476. },
  477. async onFinish(input) {
  478. const assistant = next.metadata!.assistant!
  479. const usage = getUsage(input.totalUsage, model.info)
  480. assistant.cost = usage.cost
  481. await updateMessage(next)
  482. },
  483. onError(input) {
  484. if (input.error instanceof Error) {
  485. next.metadata.error = input.error.toString()
  486. }
  487. },
  488. async prepareStep(step) {
  489. next.parts.push({
  490. type: "step-start",
  491. })
  492. await updateMessage(next)
  493. return step
  494. },
  495. toolCallStreaming: false,
  496. abortSignal: abort.signal,
  497. maxRetries: 6,
  498. stopWhen: stepCountIs(1000),
  499. messages: convertToModelMessages(msgs),
  500. temperature: 0,
  501. tools: {
  502. ...(await MCP.tools()),
  503. ...tools,
  504. },
  505. model: model.language,
  506. })
  507. await result.consumeStream()
  508. next.metadata!.time.completed = Date.now()
  509. await updateMessage(next)
  510. return next
  511. }
  512. export async function summarize(input: {
  513. sessionID: string
  514. providerID: string
  515. modelID: string
  516. }) {
  517. using abort = lock(input.sessionID)
  518. const msgs = await messages(input.sessionID)
  519. const lastSummary = msgs.findLast(
  520. (msg) => msg.metadata.assistant?.summary === true,
  521. )?.id
  522. const filtered = msgs.filter(
  523. (msg) => msg.role !== "system" && (!lastSummary || msg.id >= lastSummary),
  524. )
  525. const model = await Provider.getModel(input.providerID, input.modelID)
  526. const next: Message.Info = {
  527. id: Identifier.ascending("message"),
  528. role: "assistant",
  529. parts: [],
  530. metadata: {
  531. tool: {},
  532. sessionID: input.sessionID,
  533. assistant: {
  534. summary: true,
  535. cost: 0,
  536. modelID: input.modelID,
  537. providerID: input.providerID,
  538. tokens: {
  539. input: 0,
  540. output: 0,
  541. reasoning: 0,
  542. },
  543. },
  544. time: {
  545. created: Date.now(),
  546. },
  547. },
  548. }
  549. await updateMessage(next)
  550. const result = await generateText({
  551. abortSignal: abort.signal,
  552. model: model.language,
  553. messages: convertToModelMessages([
  554. {
  555. role: "system",
  556. parts: [
  557. {
  558. type: "text",
  559. text: PROMPT_SUMMARIZE,
  560. },
  561. ],
  562. },
  563. ...filtered,
  564. {
  565. role: "user",
  566. parts: [
  567. {
  568. type: "text",
  569. 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.",
  570. },
  571. ],
  572. },
  573. ]),
  574. })
  575. next.parts.push({
  576. type: "text",
  577. text: result.text,
  578. })
  579. const assistant = next.metadata!.assistant!
  580. const usage = getUsage(result.usage, model.info)
  581. assistant.cost = usage.cost
  582. assistant.tokens = usage.tokens
  583. await updateMessage(next)
  584. }
  585. const pending = new Map<string, AbortController>()
  586. function lock(sessionID: string) {
  587. log.info("locking", { sessionID })
  588. if (pending.has(sessionID)) throw new BusyError(sessionID)
  589. const controller = new AbortController()
  590. pending.set(sessionID, controller)
  591. return {
  592. signal: controller.signal,
  593. [Symbol.dispose]() {
  594. log.info("unlocking", { sessionID })
  595. pending.delete(sessionID)
  596. },
  597. }
  598. }
  599. function getUsage(usage: LanguageModelUsage, model: Provider.Model) {
  600. const tokens = {
  601. input: usage.inputTokens ?? 0,
  602. output: usage.outputTokens ?? 0,
  603. reasoning: usage.reasoningTokens ?? 0,
  604. }
  605. return {
  606. cost: new Decimal(0)
  607. .add(new Decimal(tokens.input).mul(model.cost.input).div(1_000_000))
  608. .add(new Decimal(tokens.output).mul(model.cost.output).div(1_000_000))
  609. .toNumber(),
  610. tokens,
  611. }
  612. }
  613. export class BusyError extends Error {
  614. constructor(public readonly sessionID: string) {
  615. super(`Session ${sessionID} is busy`)
  616. }
  617. }
  618. export async function initialize(input: {
  619. sessionID: string
  620. modelID: string
  621. providerID: string
  622. }) {
  623. await Session.chat({
  624. sessionID: input.sessionID,
  625. providerID: input.providerID,
  626. modelID: input.modelID,
  627. parts: [
  628. {
  629. type: "text",
  630. text: PROMPT_INITIALIZE,
  631. },
  632. ],
  633. })
  634. await App.initialize()
  635. }
  636. }