2025-05-31 10:14:09 +08:00
import path from "path"
import { App } from "../app/app"
import { Identifier } from "../id/id"
import { Storage } from "../storage/storage"
import { Log } from "../util/log"
2025-05-18 14:43:01 +08:00
import {
2025-05-29 05:24:15 +08:00
generateText ,
2025-06-10 02:01:11 +08:00
LoadAPIKeyError ,
2025-06-15 09:03:44 +08:00
convertToCoreMessages ,
2025-05-18 14:43:01 +08:00
streamText ,
2025-06-01 05:12:16 +08:00
tool ,
type Tool as AITool ,
2025-05-30 01:02:48 +08:00
type LanguageModelUsage ,
2025-06-15 06:43:58 +08:00
type CoreMessage ,
2025-06-15 09:03:44 +08:00
type UIMessage ,
2025-06-17 00:43:22 +08:00
type ProviderMetadata ,
2025-05-31 10:14:09 +08:00
} from "ai"
2025-06-01 05:12:16 +08:00
import { z , ZodSchema } from "zod"
2025-05-31 10:14:09 +08:00
import { Decimal } from "decimal.js"
2025-05-18 09:31:42 +08:00
2025-06-04 00:38:48 +08:00
import PROMPT_INITIALIZE from "../session/prompt/initialize.txt"
2025-05-27 09:08:15 +08:00
2025-05-31 10:14:09 +08:00
import { Share } from "../share/share"
import { Message } from "./message"
import { Bus } from "../bus"
2025-06-01 04:05:12 +08:00
import { Provider } from "../provider/provider"
2025-06-04 03:57:38 +08:00
import { MCP } from "../mcp"
2025-06-10 02:01:11 +08:00
import { NamedError } from "../util/error"
2025-06-13 05:04:34 +08:00
import type { Tool } from "../tool/tool"
import { SystemPrompt } from "./system"
2025-06-14 13:50:30 +08:00
import { Flag } from "../flag/flag"
2025-06-15 06:43:58 +08:00
import type { ModelsDev } from "../provider/models"
2025-06-19 01:40:21 +08:00
import { Installation } from "../installation"
2025-06-19 10:20:03 +08:00
import { Config } from "../config/config"
2025-06-19 22:32:14 +08:00
import { ProviderTransform } from "../provider/transform"
2025-05-20 23:11:06 +08:00
2025-05-18 09:31:42 +08:00
export namespace Session {
2025-05-31 10:14:09 +08:00
const log = Log . create ( { service : "session" } )
2025-05-18 09:31:42 +08:00
2025-05-29 23:38:55 +08:00
export const Info = z
. object ( {
id : Identifier.schema ( "session" ) ,
2025-06-13 05:04:34 +08:00
parentID : Identifier.schema ( "session" ) . optional ( ) ,
2025-05-31 01:58:46 +08:00
share : z
. object ( {
url : z.string ( ) ,
} )
. optional ( ) ,
2025-05-29 23:38:55 +08:00
title : z.string ( ) ,
2025-06-19 01:40:21 +08:00
version : z.string ( ) ,
2025-05-31 01:58:46 +08:00
time : z.object ( {
created : z.number ( ) ,
updated : z.number ( ) ,
} ) ,
2025-05-29 23:38:55 +08:00
} )
. openapi ( {
ref : "session.info" ,
2025-05-31 10:14:09 +08:00
} )
export type Info = z . output < typeof Info >
2025-05-18 09:31:42 +08:00
2025-06-19 04:13:09 +08:00
export const ShareInfo = z . object ( {
secret : z.string ( ) ,
url : z.string ( ) ,
} )
export type ShareInfo = z . output < typeof ShareInfo >
2025-05-29 23:17:34 +08:00
export const Event = {
Updated : Bus.event (
"session.updated" ,
2025-05-29 23:32:55 +08:00
z . object ( {
2025-05-29 23:35:56 +08:00
info : Info ,
2025-05-29 23:17:34 +08:00
} ) ,
) ,
2025-06-10 02:01:11 +08:00
Error : Bus . event (
"session.error" ,
z . object ( {
error : Message.Info.shape.metadata.shape.error ,
} ) ,
) ,
2025-05-31 10:14:09 +08:00
}
2025-05-29 23:17:34 +08:00
2025-06-19 02:11:33 +08:00
const state = App . state (
"session" ,
( ) = > {
const sessions = new Map < string , Info > ( )
const messages = new Map < string , Message.Info [ ] > ( )
const pending = new Map < string , AbortController > ( )
return {
sessions ,
messages ,
pending ,
}
} ,
async ( state ) = > {
for ( const [ _ , controller ] of state . pending ) {
controller . abort ( )
}
} ,
)
2025-05-18 14:43:01 +08:00
2025-06-13 05:04:34 +08:00
export async function create ( parentID? : string ) {
2025-05-18 09:31:42 +08:00
const result : Info = {
2025-05-18 14:50:38 +08:00
id : Identifier.descending ( "session" ) ,
2025-06-19 01:40:21 +08:00
version : Installation.VERSION ,
2025-06-13 05:04:34 +08:00
parentID ,
2025-06-13 05:57:57 +08:00
title :
( parentID ? "Child session - " : "New Session - " ) +
new Date ( ) . toISOString ( ) ,
2025-05-31 01:58:46 +08:00
time : {
created : Date.now ( ) ,
updated : Date.now ( ) ,
} ,
2025-05-31 10:14:09 +08:00
}
log . info ( "created" , result )
state ( ) . sessions . set ( result . id , result )
await Storage . writeJSON ( "session/info/" + result . id , result )
2025-06-19 10:20:03 +08:00
const cfg = await Config . get ( )
2025-06-17 13:45:32 +08:00
if ( ! result . parentID && ( Flag . OPENCODE_AUTO_SHARE || cfg . autoshare ) )
2025-06-14 13:50:30 +08:00
share ( result . id ) . then ( ( share ) = > {
update ( result . id , ( draft ) = > {
draft . share = share
} )
} )
2025-05-29 23:17:34 +08:00
Bus . publish ( Event . Updated , {
2025-05-29 23:35:56 +08:00
info : result ,
2025-05-31 10:14:09 +08:00
} )
return result
2025-05-18 09:31:42 +08:00
}
2025-05-18 14:43:01 +08:00
export async function get ( id : string ) {
2025-05-31 10:14:09 +08:00
const result = state ( ) . sessions . get ( id )
2025-05-18 14:43:01 +08:00
if ( result ) {
2025-05-31 10:14:09 +08:00
return result
2025-05-18 14:43:01 +08:00
}
2025-05-31 10:14:09 +08:00
const read = await Storage . readJSON < Info > ( "session/info/" + id )
state ( ) . sessions . set ( id , read )
return read as Info
2025-05-19 02:13:04 +08:00
}
2025-06-19 04:13:09 +08:00
export async function getShare ( id : string ) {
return Storage . readJSON < ShareInfo > ( "session/share/" + id )
}
2025-05-24 04:20:21 +08:00
export async function share ( id : string ) {
2025-05-31 10:14:09 +08:00
const session = await get ( id )
if ( session . share ) return session . share
const share = await Share . create ( id )
2025-05-27 09:22:38 +08:00
await update ( id , ( draft ) = > {
2025-06-19 04:13:09 +08:00
draft . share = {
url : share.url ,
}
2025-05-31 10:14:09 +08:00
} )
2025-06-19 04:13:09 +08:00
await Storage . writeJSON < ShareInfo > ( "session/share/" + id , share )
2025-06-19 21:41:11 +08:00
await Share . sync ( "session/info/" + id , session )
2025-05-31 10:14:09 +08:00
for ( const msg of await messages ( id ) ) {
await Share . sync ( "session/message/" + id + "/" + msg . id , msg )
}
return share
2025-05-24 04:20:21 +08:00
}
2025-05-27 09:13:46 +08:00
export async function update ( id : string , editor : ( session : Info ) = > void ) {
2025-05-31 10:14:09 +08:00
const { sessions } = state ( )
const session = await get ( id )
if ( ! session ) return
editor ( session )
session . time . updated = Date . now ( )
sessions . set ( id , session )
await Storage . writeJSON ( "session/info/" + id , session )
2025-05-29 23:17:34 +08:00
Bus . publish ( Event . Updated , {
2025-05-29 23:35:56 +08:00
info : session ,
2025-05-31 10:14:09 +08:00
} )
return session
2025-05-18 14:43:01 +08:00
}
export async function messages ( sessionID : string ) {
2025-05-31 10:14:09 +08:00
const result = [ ] as Message . Info [ ]
const list = Storage . list ( "session/message/" + sessionID )
2025-05-27 01:21:15 +08:00
for await ( const p of list ) {
2025-06-12 06:19:15 +08:00
const read = await Storage . readJSON < Message.Info > ( p )
2025-05-31 10:14:09 +08:00
result . push ( read )
2025-05-18 14:43:01 +08:00
}
2025-05-31 10:14:09 +08:00
result . sort ( ( a , b ) = > ( a . id > b . id ? 1 : - 1 ) )
return result
2025-05-18 14:43:01 +08:00
}
2025-06-12 06:19:15 +08:00
export async function getMessage ( sessionID : string , messageID : string ) {
return Storage . readJSON < Message.Info > (
"session/message/" + sessionID + "/" + messageID ,
)
}
2025-05-18 14:43:01 +08:00
export async function * list() {
2025-05-27 01:21:15 +08:00
for await ( const item of Storage . list ( "session/info" ) ) {
2025-05-31 10:14:09 +08:00
const sessionID = path . basename ( item , ".json" )
yield get ( sessionID )
2025-05-18 14:43:01 +08:00
}
}
2025-05-29 03:07:51 +08:00
export function abort ( sessionID : string ) {
2025-06-19 02:11:33 +08:00
const controller = state ( ) . pending . get ( sessionID )
2025-05-31 10:14:09 +08:00
if ( ! controller ) return false
controller . abort ( )
2025-06-19 02:11:33 +08:00
state ( ) . pending . delete ( sessionID )
2025-05-31 10:14:09 +08:00
return true
2025-05-29 03:07:51 +08:00
}
2025-05-30 01:02:48 +08:00
async function updateMessage ( msg : Message.Info ) {
await Storage . writeJSON (
"session/message/" + msg . metadata . sessionID + "/" + msg . id ,
msg ,
2025-05-31 10:14:09 +08:00
)
2025-05-30 01:02:48 +08:00
Bus . publish ( Message . Event . Updated , {
info : msg ,
2025-05-31 10:14:09 +08:00
} )
2025-05-30 01:02:48 +08:00
}
2025-05-29 00:53:22 +08:00
export async function chat ( input : {
2025-05-31 10:14:09 +08:00
sessionID : string
providerID : string
modelID : string
parts : Message.Part [ ]
2025-06-13 05:04:34 +08:00
system? : string [ ]
tools? : Tool.Info [ ]
2025-05-29 00:53:22 +08:00
} ) {
2025-05-31 10:14:09 +08:00
const l = log . clone ( ) . tag ( "session" , input . sessionID )
l . info ( "chatting" )
2025-06-01 04:05:12 +08:00
const model = await Provider . getModel ( input . providerID , input . modelID )
2025-05-31 10:14:09 +08:00
let msgs = await messages ( input . sessionID )
const previous = msgs . at ( - 1 )
2025-06-13 05:04:34 +08:00
// auto summarize if too long
2025-05-30 02:16:15 +08:00
if ( previous ? . metadata . assistant ) {
const tokens =
previous . metadata . assistant . tokens . input +
2025-06-17 00:43:22 +08:00
previous . metadata . assistant . tokens . cache . read +
previous . metadata . assistant . tokens . cache . write +
2025-05-31 10:14:09 +08:00
previous . metadata . assistant . tokens . output
2025-05-30 02:16:15 +08:00
if (
2025-06-17 22:50:03 +08:00
model . info . limit . context &&
2025-05-30 02:16:15 +08:00
tokens >
2025-06-17 22:50:03 +08:00
( model . info . limit . context - ( model . info . limit . output ? ? 0 ) ) * 0.9
2025-05-30 02:16:15 +08:00
) {
await summarize ( {
sessionID : input.sessionID ,
providerID : input.providerID ,
modelID : input.modelID ,
2025-05-31 10:14:09 +08:00
} )
return chat ( input )
2025-05-30 02:16:15 +08:00
}
}
2025-05-31 10:14:09 +08:00
using abort = lock ( input . sessionID )
2025-05-30 02:16:15 +08:00
2025-05-30 01:02:48 +08:00
const lastSummary = msgs . findLast (
( msg ) = > msg . metadata . assistant ? . summary === true ,
2025-05-31 10:14:09 +08:00
)
2025-06-13 05:04:34 +08:00
if ( lastSummary ) msgs = msgs . filter ( ( msg ) = > msg . id >= lastSummary . id )
2025-05-30 01:02:48 +08:00
2025-06-13 05:04:34 +08:00
const app = App . info ( )
2025-06-13 05:57:57 +08:00
const session = await get ( input . sessionID )
if ( msgs . length === 0 && ! session . parentID ) {
2025-05-27 09:08:15 +08:00
generateText ( {
2025-06-15 06:43:58 +08:00
maxTokens : input.providerID === "google" ? 1024 : 20 ,
messages : [
2025-06-13 05:04:34 +08:00
. . . SystemPrompt . title ( input . providerID ) . map (
2025-06-15 06:43:58 +08:00
( x ) : CoreMessage = > ( {
2025-06-13 05:04:34 +08:00
role : "system" ,
2025-06-15 06:43:58 +08:00
content : x ,
2025-06-13 05:04:34 +08:00
} ) ,
) ,
2025-06-15 09:03:44 +08:00
. . . convertToCoreMessages ( [
{
role : "user" ,
content : "" ,
parts : toParts ( input . parts ) ,
} ,
] ) ,
2025-06-19 22:32:14 +08:00
] . map ( ( msg , i ) = >
ProviderTransform . message ( msg , i , input . providerID , input . modelID ) ,
) ,
2025-06-01 04:05:12 +08:00
model : model.language ,
2025-05-31 10:14:09 +08:00
} )
2025-06-10 02:01:11 +08:00
. then ( ( result ) = > {
2025-06-15 06:43:58 +08:00
if ( result . text )
return Session . update ( input . sessionID , ( draft ) = > {
draft . title = result . text
} )
2025-06-10 02:01:11 +08:00
} )
2025-06-17 00:43:22 +08:00
. catch ( ( ) = > { } )
2025-05-18 14:43:01 +08:00
}
2025-05-29 22:21:59 +08:00
const msg : Message.Info = {
2025-05-19 02:13:04 +08:00
role : "user" ,
id : Identifier.ascending ( "message" ) ,
2025-05-29 00:53:22 +08:00
parts : input.parts ,
2025-05-19 02:13:04 +08:00
metadata : {
2025-05-20 23:11:06 +08:00
time : {
created : Date.now ( ) ,
} ,
2025-05-29 00:53:22 +08:00
sessionID : input.sessionID ,
2025-05-20 23:11:06 +08:00
tool : { } ,
2025-05-19 02:13:04 +08:00
} ,
2025-05-31 10:14:09 +08:00
}
await updateMessage ( msg )
msgs . push ( msg )
2025-05-18 14:43:01 +08:00
2025-06-13 05:04:34 +08:00
const system = input . system ? ? SystemPrompt . provider ( input . providerID )
2025-06-16 23:41:45 +08:00
system . push ( . . . ( await SystemPrompt . environment ( ) ) )
2025-06-13 05:04:34 +08:00
system . push ( . . . ( await SystemPrompt . custom ( ) ) )
2025-05-29 22:21:59 +08:00
const next : Message.Info = {
2025-05-29 00:53:22 +08:00
id : Identifier.ascending ( "message" ) ,
role : "assistant" ,
parts : [ ] ,
metadata : {
2025-05-29 03:39:51 +08:00
assistant : {
2025-06-13 05:04:34 +08:00
system ,
path : {
cwd : app.path.cwd ,
root : app.path.root ,
} ,
2025-05-29 03:39:51 +08:00
cost : 0 ,
tokens : {
input : 0 ,
output : 0 ,
reasoning : 0 ,
2025-06-17 00:43:22 +08:00
cache : { read : 0 , write : 0 } ,
2025-05-29 03:39:51 +08:00
} ,
modelID : input.modelID ,
providerID : input.providerID ,
} ,
2025-05-29 00:53:22 +08:00
time : {
created : Date.now ( ) ,
} ,
sessionID : input.sessionID ,
tool : { } ,
} ,
2025-05-31 10:14:09 +08:00
}
await updateMessage ( next )
2025-06-01 05:12:16 +08:00
const tools : Record < string , AITool > = { }
2025-06-13 05:04:34 +08:00
2025-06-01 05:12:16 +08:00
for ( const item of await Provider . tools ( input . providerID ) ) {
tools [ item . id . replaceAll ( "." , "_" ) ] = tool ( {
id : item.id as any ,
description : item.description ,
parameters : item.parameters as ZodSchema ,
async execute ( args , opts ) {
const start = Date . now ( )
try {
2025-06-03 07:51:26 +08:00
const result = await item . execute ( args , {
sessionID : input.sessionID ,
2025-06-11 05:56:05 +08:00
abort : abort.signal ,
2025-06-13 05:04:34 +08:00
messageID : next.id ,
2025-06-19 01:40:21 +08:00
metadata : async ( val ) = > {
next . metadata . tool [ opts . toolCallId ] = {
. . . val ,
time : {
start : 0 ,
end : 0 ,
} ,
}
await updateMessage ( next )
} ,
2025-06-03 07:51:26 +08:00
} )
2025-06-01 05:12:16 +08:00
next . metadata ! . tool ! [ opts . toolCallId ] = {
. . . result . metadata ,
time : {
start ,
end : Date.now ( ) ,
} ,
}
2025-06-12 06:19:15 +08:00
await updateMessage ( next )
2025-06-01 05:12:16 +08:00
return result . output
} catch ( e : any ) {
next . metadata ! . tool ! [ opts . toolCallId ] = {
error : true ,
message : e.toString ( ) ,
2025-06-12 06:19:15 +08:00
title : e.toString ( ) ,
2025-06-01 05:12:16 +08:00
time : {
start ,
end : Date.now ( ) ,
} ,
}
2025-06-12 06:19:15 +08:00
await updateMessage ( next )
2025-06-01 05:12:16 +08:00
return e . toString ( )
}
} ,
} )
}
2025-06-13 05:04:34 +08:00
2025-06-04 03:57:38 +08:00
for ( const [ key , item ] of Object . entries ( await MCP . tools ( ) ) ) {
const execute = item . execute
if ( ! execute ) continue
item . execute = async ( args , opts ) = > {
const start = Date . now ( )
try {
const result = await execute ( args , opts )
next . metadata ! . tool ! [ opts . toolCallId ] = {
. . . result . metadata ,
time : {
start ,
end : Date.now ( ) ,
} ,
}
2025-06-12 06:19:15 +08:00
await updateMessage ( next )
2025-06-04 03:57:38 +08:00
return result . content
. filter ( ( x : any ) = > x . type === "text" )
. map ( ( x : any ) = > x . text )
. join ( "\n\n" )
} catch ( e : any ) {
next . metadata ! . tool ! [ opts . toolCallId ] = {
error : true ,
message : e.toString ( ) ,
2025-06-12 06:19:15 +08:00
title : "mcp" ,
2025-06-04 03:57:38 +08:00
time : {
start ,
end : Date.now ( ) ,
} ,
}
2025-06-12 06:19:15 +08:00
await updateMessage ( next )
2025-06-04 03:57:38 +08:00
return e . toString ( )
}
}
tools [ key ] = item
}
2025-06-05 05:55:07 +08:00
let text : Message.TextPart | undefined
2025-06-16 23:41:45 +08:00
await Bun . write (
"/tmp/message.json" ,
JSON . stringify (
[
. . . system . map (
( x ) : CoreMessage = > ( {
role : "system" ,
content : x ,
} ) ,
) ,
. . . convertToCoreMessages (
msgs . map ( toUIMessage ) . filter ( ( x ) = > x . parts . length > 0 ) ,
) ,
] ,
null ,
2 ,
) ,
)
2025-05-18 14:43:01 +08:00
const result = streamText ( {
2025-05-29 03:39:51 +08:00
onStepFinish : async ( step ) = > {
2025-06-17 04:02:45 +08:00
log . info ( "step finish" , { finishReason : step.finishReason } )
2025-05-31 10:14:09 +08:00
const assistant = next . metadata ! . assistant !
2025-06-17 00:43:22 +08:00
const usage = getUsage ( model . info , step . usage , step . providerMetadata )
2025-06-05 14:23:11 +08:00
assistant . cost += usage . cost
2025-05-31 10:14:09 +08:00
assistant . tokens = usage . tokens
await updateMessage ( next )
2025-06-05 08:49:28 +08:00
if ( text ) {
Bus . publish ( Message . Event . PartUpdated , {
part : text ,
2025-06-12 06:19:15 +08:00
messageID : next.id ,
sessionID : next.metadata.sessionID ,
2025-06-05 08:49:28 +08:00
} )
}
2025-06-05 05:55:07 +08:00
text = undefined
} ,
2025-06-05 14:23:11 +08:00
async onFinish ( input ) {
2025-06-17 04:02:45 +08:00
log . info ( "message finish" , {
reason : input.finishReason ,
} )
2025-06-05 14:23:11 +08:00
const assistant = next . metadata ! . assistant !
2025-06-17 00:43:22 +08:00
const usage = getUsage ( model . info , input . usage , input . providerMetadata )
2025-06-05 14:23:11 +08:00
assistant . cost = usage . cost
await updateMessage ( next )
} ,
2025-06-10 02:01:11 +08:00
onError ( err ) {
2025-06-15 09:23:57 +08:00
log . error ( "callback error" , err )
2025-06-10 02:01:11 +08:00
switch ( true ) {
case LoadAPIKeyError . isInstance ( err . error ) :
next . metadata . error = new Provider . AuthError (
{
providerID : input.providerID ,
message : err.error.message ,
} ,
{ cause : err.error } ,
) . toObject ( )
break
case err . error instanceof Error :
next . metadata . error = new NamedError . Unknown (
{ message : err.error.toString ( ) } ,
{ cause : err.error } ,
) . toObject ( )
2025-06-11 23:41:10 +08:00
break
default :
next . metadata . error = new NamedError . Unknown (
{ message : JSON.stringify ( err . error ) } ,
{ cause : err.error } ,
)
2025-06-05 05:55:07 +08:00
}
2025-06-10 02:01:11 +08:00
Bus . publish ( Event . Error , {
error : next.metadata.error ,
} )
2025-05-27 10:35:30 +08:00
} ,
2025-06-15 06:43:58 +08:00
// async prepareStep(step) {
// next.parts.push({
// type: "step-start",
// })
// await updateMessage(next)
// return step
// },
2025-06-12 12:50:49 +08:00
toolCallStreaming : true ,
2025-05-30 01:02:48 +08:00
abortSignal : abort.signal ,
2025-06-15 06:43:58 +08:00
maxSteps : 1000 ,
messages : [
2025-06-13 05:04:34 +08:00
. . . system . map (
2025-06-19 22:32:14 +08:00
( x ) : CoreMessage = > ( {
2025-06-13 05:04:34 +08:00
role : "system" ,
2025-06-15 06:43:58 +08:00
content : x ,
2025-06-13 05:04:34 +08:00
} ) ,
) ,
2025-06-15 09:03:44 +08:00
. . . convertToCoreMessages (
msgs . map ( toUIMessage ) . filter ( ( x ) = > x . parts . length > 0 ) ,
) ,
2025-06-19 22:32:14 +08:00
] . map ( ( msg , i ) = >
ProviderTransform . message ( msg , i , input . providerID , input . modelID ) ,
) ,
2025-06-17 23:27:07 +08:00
temperature : model.info.temperature ? 0 : undefined ,
2025-06-04 03:57:38 +08:00
tools : {
. . . tools ,
} ,
2025-06-01 04:05:12 +08:00
model : model.language ,
2025-05-31 10:14:09 +08:00
} )
2025-06-15 09:23:57 +08:00
try {
for await ( const value of result . fullStream ) {
l . info ( "part" , {
type : value . type ,
} )
switch ( value . type ) {
case "step-start" :
next . parts . push ( {
type : "step-start" ,
} )
break
case "text-delta" :
if ( ! text ) {
text = {
type : "text" ,
text : value.textDelta ,
}
next . parts . push ( text )
break
} else text . text += value . textDelta
2025-06-15 06:43:58 +08:00
break
2025-06-15 09:23:57 +08:00
case "tool-call" : {
const [ match ] = next . parts . flatMap ( ( p ) = >
2025-06-15 06:43:58 +08:00
p . type === "tool-invocation" &&
2025-06-15 09:23:57 +08:00
p . toolInvocation . toolCallId === value . toolCallId
? [ p ]
: [ ] ,
)
if ( ! match ) break
match . toolInvocation . args = value . args
match . toolInvocation . state = "call"
2025-06-15 06:43:58 +08:00
Bus . publish ( Message . Event . PartUpdated , {
part : match ,
messageID : next.id ,
sessionID : next.metadata.sessionID ,
} )
2025-06-15 09:23:57 +08:00
break
2025-06-15 06:43:58 +08:00
}
2025-06-15 09:23:57 +08:00
case "tool-call-streaming-start" :
next . parts . push ( {
type : "tool-invocation" ,
toolInvocation : {
state : "partial-call" ,
toolName : value.toolName ,
toolCallId : value.toolCallId ,
args : { } ,
} ,
} )
Bus . publish ( Message . Event . PartUpdated , {
part : next.parts [ next . parts . length - 1 ] ,
messageID : next.id ,
sessionID : next.metadata.sessionID ,
} )
break
case "tool-call-delta" :
break
// for some reason ai sdk claims to not send this part but it does
// @ts-expect-error
case "tool-result" :
const match = next . parts . find (
( p ) = >
p . type === "tool-invocation" &&
// @ts-expect-error
p . toolInvocation . toolCallId === value . toolCallId ,
)
if ( match && match . type === "tool-invocation" ) {
match . toolInvocation = {
// @ts-expect-error
args : value.args ,
// @ts-expect-error
toolCallId : value.toolCallId ,
// @ts-expect-error
toolName : value.toolName ,
state : "result" ,
// @ts-expect-error
result : value.result as string ,
}
Bus . publish ( Message . Event . PartUpdated , {
part : match ,
messageID : next.id ,
sessionID : next.metadata.sessionID ,
} )
}
break
default :
l . info ( "unhandled" , {
type : value . type ,
} )
}
await updateMessage ( next )
}
} catch ( e : any ) {
log . error ( "stream error" , {
error : e ,
} )
switch ( true ) {
case LoadAPIKeyError . isInstance ( e ) :
next . metadata . error = new Provider . AuthError (
{
providerID : input.providerID ,
message : e.message ,
} ,
{ cause : e } ,
) . toObject ( )
break
case e instanceof Error :
next . metadata . error = new NamedError . Unknown (
{ message : e.toString ( ) } ,
{ cause : e } ,
) . toObject ( )
break
2025-06-15 06:43:58 +08:00
default :
2025-06-15 09:23:57 +08:00
next . metadata . error = new NamedError . Unknown (
{ message : JSON.stringify ( e ) } ,
{ cause : e } ,
)
2025-06-15 06:43:58 +08:00
}
2025-06-15 09:23:57 +08:00
Bus . publish ( Event . Error , {
error : next.metadata.error ,
} )
2025-06-15 06:43:58 +08:00
}
2025-05-31 10:14:09 +08:00
next . metadata ! . time . completed = Date . now ( )
2025-06-10 08:48:50 +08:00
for ( const part of next . parts ) {
if (
part . type === "tool-invocation" &&
part . toolInvocation . state !== "result"
) {
part . toolInvocation = {
. . . part . toolInvocation ,
state : "result" ,
result : "request was aborted" ,
}
}
}
2025-05-31 10:14:09 +08:00
await updateMessage ( next )
return next
2025-05-18 14:43:01 +08:00
}
2025-05-30 01:02:48 +08:00
export async function summarize ( input : {
2025-05-31 10:14:09 +08:00
sessionID : string
providerID : string
modelID : string
2025-05-30 01:02:48 +08:00
} ) {
2025-05-31 10:14:09 +08:00
using abort = lock ( input . sessionID )
const msgs = await messages ( input . sessionID )
2025-05-30 01:02:48 +08:00
const lastSummary = msgs . findLast (
( msg ) = > msg . metadata . assistant ? . summary === true ,
2025-05-31 10:14:09 +08:00
) ? . id
2025-06-13 05:04:34 +08:00
const filtered = msgs . filter ( ( msg ) = > ! lastSummary || msg . id >= lastSummary )
2025-06-01 04:05:12 +08:00
const model = await Provider . getModel ( input . providerID , input . modelID )
2025-06-13 05:04:34 +08:00
const app = App . info ( )
const system = SystemPrompt . summarize ( input . providerID )
2025-05-30 01:02:48 +08:00
const next : Message.Info = {
id : Identifier.ascending ( "message" ) ,
role : "assistant" ,
parts : [ ] ,
metadata : {
tool : { } ,
sessionID : input.sessionID ,
assistant : {
2025-06-13 05:04:34 +08:00
system ,
path : {
cwd : app.path.cwd ,
root : app.path.root ,
} ,
2025-05-30 01:02:48 +08:00
summary : true ,
cost : 0 ,
modelID : input.modelID ,
providerID : input.providerID ,
tokens : {
input : 0 ,
output : 0 ,
reasoning : 0 ,
2025-06-17 00:43:22 +08:00
cache : { read : 0 , write : 0 } ,
2025-05-30 01:02:48 +08:00
} ,
} ,
time : {
created : Date.now ( ) ,
} ,
} ,
2025-05-31 10:14:09 +08:00
}
await updateMessage ( next )
2025-05-30 01:02:48 +08:00
const result = await generateText ( {
abortSignal : abort.signal ,
2025-06-01 04:05:12 +08:00
model : model.language ,
2025-06-15 06:43:58 +08:00
messages : [
2025-06-13 05:04:34 +08:00
. . . system . map (
2025-06-15 06:43:58 +08:00
( x ) : CoreMessage = > ( {
2025-06-13 05:04:34 +08:00
role : "system" ,
2025-06-15 06:43:58 +08:00
content : x ,
2025-06-13 05:04:34 +08:00
} ) ,
) ,
2025-06-15 09:03:44 +08:00
. . . convertToCoreMessages ( filtered . map ( toUIMessage ) ) ,
2025-05-30 01:02:48 +08:00
{
role : "user" ,
2025-06-15 09:03:44 +08:00
content : [
2025-05-30 01:02:48 +08:00
{
type : "text" ,
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." ,
} ,
2025-06-15 09:03:44 +08:00
] ,
2025-05-30 01:02:48 +08:00
} ,
2025-06-15 06:43:58 +08:00
] ,
2025-05-31 10:14:09 +08:00
} )
2025-05-30 01:02:48 +08:00
next . parts . push ( {
type : "text" ,
text : result.text ,
2025-05-31 10:14:09 +08:00
} )
const assistant = next . metadata ! . assistant !
2025-06-17 00:43:22 +08:00
const usage = getUsage ( model . info , result . usage , result . providerMetadata )
2025-05-31 10:14:09 +08:00
assistant . cost = usage . cost
assistant . tokens = usage . tokens
await updateMessage ( next )
2025-05-30 01:02:48 +08:00
}
function lock ( sessionID : string ) {
2025-05-31 10:14:09 +08:00
log . info ( "locking" , { sessionID } )
2025-06-19 02:11:33 +08:00
if ( state ( ) . pending . has ( sessionID ) ) throw new BusyError ( sessionID )
2025-05-31 10:14:09 +08:00
const controller = new AbortController ( )
2025-06-19 02:11:33 +08:00
state ( ) . pending . set ( sessionID , controller )
2025-05-30 01:02:48 +08:00
return {
signal : controller.signal ,
[ Symbol . dispose ] ( ) {
2025-05-31 10:14:09 +08:00
log . info ( "unlocking" , { sessionID } )
2025-06-19 02:11:33 +08:00
state ( ) . pending . delete ( sessionID )
2025-05-30 01:02:48 +08:00
} ,
2025-05-31 10:14:09 +08:00
}
2025-05-30 01:02:48 +08:00
}
2025-06-17 00:43:22 +08:00
function getUsage (
model : ModelsDev.Model ,
usage : LanguageModelUsage ,
metadata? : ProviderMetadata ,
) {
2025-05-30 01:02:48 +08:00
const tokens = {
2025-06-15 06:43:58 +08:00
input : usage.promptTokens ? ? 0 ,
output : usage.completionTokens ? ? 0 ,
reasoning : 0 ,
2025-06-17 00:43:22 +08:00
cache : {
write : ( metadata ? . [ "anthropic" ] ? . [ "cacheCreationInputTokens" ] ? ?
0 ) as number ,
read : ( metadata ? . [ "anthropic" ] ? . [ "cacheReadInputTokens" ] ? ?
0 ) as number ,
} ,
2025-05-31 10:14:09 +08:00
}
2025-05-30 01:02:48 +08:00
return {
cost : new Decimal ( 0 )
2025-06-06 03:06:42 +08:00
. add ( new Decimal ( tokens . input ) . mul ( model . cost . input ) . div ( 1 _000_000 ) )
. add ( new Decimal ( tokens . output ) . mul ( model . cost . output ) . div ( 1 _000_000 ) )
2025-06-18 08:51:25 +08:00
. add (
new Decimal ( tokens . cache . read )
. mul ( model . cost . cache_read ? ? 0 )
. div ( 1 _000_000 ) ,
)
. add (
new Decimal ( tokens . cache . write )
. mul ( model . cost . cache_write ? ? 0 )
. div ( 1 _000_000 ) ,
)
2025-05-30 01:02:48 +08:00
. toNumber ( ) ,
tokens ,
2025-05-31 10:14:09 +08:00
}
2025-05-30 01:02:48 +08:00
}
export class BusyError extends Error {
constructor ( public readonly sessionID : string ) {
2025-05-31 10:14:09 +08:00
super ( ` Session ${ sessionID } is busy ` )
2025-05-30 01:02:48 +08:00
}
}
2025-06-04 00:38:48 +08:00
export async function initialize ( input : {
sessionID : string
modelID : string
providerID : string
} ) {
2025-06-10 03:28:06 +08:00
const app = App . info ( )
2025-06-04 00:38:48 +08:00
await Session . chat ( {
sessionID : input.sessionID ,
providerID : input.providerID ,
modelID : input.modelID ,
parts : [
{
type : "text" ,
2025-06-10 03:28:06 +08:00
text : PROMPT_INITIALIZE.replace ( "${path}" , app . path . root ) ,
2025-06-04 00:38:48 +08:00
} ,
] ,
} )
2025-06-04 02:24:45 +08:00
await App . initialize ( )
2025-06-04 00:38:48 +08:00
}
2025-05-18 09:31:42 +08:00
}
2025-06-15 06:43:58 +08:00
2025-06-15 09:03:44 +08:00
function toUIMessage ( msg : Message.Info ) : UIMessage {
if ( msg . role === "assistant" ) {
return {
id : msg.id ,
role : "assistant" ,
content : "" ,
parts : toParts ( msg . parts ) ,
}
}
if ( msg . role === "user" ) {
return {
id : msg.id ,
role : "user" ,
content : "" ,
parts : toParts ( msg . parts ) ,
}
}
throw new Error ( "not implemented" )
}
function toParts ( parts : Message.Part [ ] ) : UIMessage [ "parts" ] {
const result : UIMessage [ "parts" ] = [ ]
2025-06-15 06:43:58 +08:00
for ( const part of parts ) {
switch ( part . type ) {
case "text" :
result . push ( { type : "text" , text : part.text } )
break
case "file" :
result . push ( {
type : "file" ,
2025-06-15 09:03:44 +08:00
data : part.url ,
2025-06-15 06:43:58 +08:00
mimeType : part.mediaType ,
} )
break
case "tool-invocation" :
result . push ( {
2025-06-15 09:03:44 +08:00
type : "tool-invocation" ,
toolInvocation : part.toolInvocation ,
2025-06-15 06:43:58 +08:00
} )
break
2025-06-15 09:03:44 +08:00
case "step-start" :
result . push ( {
type : "step-start" ,
} )
2025-06-15 06:43:58 +08:00
break
default :
2025-06-15 09:03:44 +08:00
break
2025-06-15 06:43:58 +08:00
}
}
return result
}