1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
|
import path from "path";
import { App } from "../app/app";
import { Identifier } from "../id/id";
import { LLM } from "../llm/llm";
import { Storage } from "../storage/storage";
import { Log } from "../util/log";
import {
convertToModelMessages,
generateText,
stepCountIs,
streamText,
type LanguageModelUsage,
} from "ai";
import { z } from "zod";
import * as tools from "../tool";
import { Decimal } from "decimal.js";
import PROMPT_ANTHROPIC from "./prompt/anthropic.txt";
import PROMPT_TITLE from "./prompt/title.txt";
import PROMPT_SUMMARIZE from "./prompt/summarize.txt";
import { Share } from "../share/share";
import { Message } from "./message";
import { Bus } from "../bus";
import type { Provider } from "../provider/provider";
export namespace Session {
const log = Log.create({ service: "session" });
export const Info = z
.object({
id: Identifier.schema("session"),
shareID: z.string().optional(),
title: z.string(),
})
.openapi({
ref: "session.info",
});
export type Info = z.output<typeof Info>;
export const Event = {
Updated: Bus.event(
"session.updated",
z.object({
info: Info,
}),
),
};
const state = App.state("session", () => {
const sessions = new Map<string, Info>();
const messages = new Map<string, Message.Info[]>();
return {
sessions,
messages,
};
});
export async function create() {
const result: Info = {
id: Identifier.descending("session"),
title: "New Session - " + new Date().toISOString(),
};
log.info("created", result);
state().sessions.set(result.id, result);
await Storage.writeJSON("session/info/" + result.id, result);
share(result.id).then((shareID) => {
update(result.id, (draft) => {
draft.shareID = shareID;
});
});
Bus.publish(Event.Updated, {
info: result,
});
return result;
}
export async function get(id: string) {
const result = state().sessions.get(id);
if (result) {
return result;
}
const read = await Storage.readJSON<Info>("session/info/" + id);
state().sessions.set(id, read);
return read as Info;
}
export async function share(id: string) {
const session = await get(id);
if (session.shareID) return session.shareID;
const shareID = await Share.create(id);
if (!shareID) return;
await update(id, (draft) => {
draft.shareID = shareID;
});
return shareID as string;
}
export async function update(id: string, editor: (session: Info) => void) {
const { sessions } = state();
const session = await get(id);
if (!session) return;
editor(session);
sessions.set(id, session);
await Storage.writeJSON("session/info/" + id, session);
Bus.publish(Event.Updated, {
info: session,
});
return session;
}
export async function messages(sessionID: string) {
const result = [] as Message.Info[];
const list = Storage.list("session/message/" + sessionID);
for await (const p of list) {
const read = await Storage.readJSON<Message.Info>(p).catch(() => {});
if (!read) continue;
result.push(read);
}
result.sort((a, b) => (a.id > b.id ? 1 : -1));
return result;
}
export async function* list() {
for await (const item of Storage.list("session/info")) {
const sessionID = path.basename(item, ".json");
yield get(sessionID);
}
}
export function abort(sessionID: string) {
const controller = pending.get(sessionID);
if (!controller) return false;
controller.abort();
pending.delete(sessionID);
return true;
}
async function updateMessage(msg: Message.Info) {
await Storage.writeJSON(
"session/message/" + msg.metadata.sessionID + "/" + msg.id,
msg,
);
Bus.publish(Message.Event.Updated, {
info: msg,
});
}
export async function chat(input: {
sessionID: string;
providerID: string;
modelID: string;
parts: Message.Part[];
}) {
const l = log.clone().tag("session", input.sessionID);
l.info("chatting");
const model = await LLM.findModel(input.providerID, input.modelID);
let msgs = await messages(input.sessionID);
const previous = msgs.at(-1);
if (previous?.metadata.assistant) {
const tokens =
previous.metadata.assistant.tokens.input +
previous.metadata.assistant.tokens.output;
if (
tokens >
(model.info.contextWindow - (model.info.maxOutputTokens ?? 0)) * 0.9
) {
await summarize({
sessionID: input.sessionID,
providerID: input.providerID,
modelID: input.modelID,
});
return chat(input);
}
}
using abort = lock(input.sessionID);
const lastSummary = msgs.findLast(
(msg) => msg.metadata.assistant?.summary === true,
);
if (lastSummary)
msgs = msgs.filter(
(msg) => msg.role === "system" || msg.id >= lastSummary.id,
);
const app = await App.use();
if (msgs.length === 0) {
const system: Message.Info = {
id: Identifier.ascending("message"),
role: "system",
parts: [
{
type: "text",
text: PROMPT_ANTHROPIC,
},
],
metadata: {
sessionID: input.sessionID,
time: {
created: Date.now(),
},
tool: {},
},
};
const contextFile = Bun.file(path.join(app.root, "CONTEXT.md"));
if (await contextFile.exists()) {
const context = await contextFile.text();
system.parts.push({
type: "text",
text: context,
});
}
msgs.push(system);
generateText({
messages: convertToModelMessages([
{
role: "system",
parts: [
{
type: "text",
text: PROMPT_TITLE,
},
],
},
{
role: "user",
parts: input.parts,
},
]),
model: model.instance,
}).then((result) => {
return Session.update(input.sessionID, (draft) => {
draft.title = result.text;
});
});
await updateMessage(system);
}
const msg: Message.Info = {
role: "user",
id: Identifier.ascending("message"),
parts: input.parts,
metadata: {
time: {
created: Date.now(),
},
sessionID: input.sessionID,
tool: {},
},
};
msgs.push(msg);
await updateMessage(msg);
const next: Message.Info = {
id: Identifier.ascending("message"),
role: "assistant",
parts: [],
metadata: {
assistant: {
cost: 0,
tokens: {
input: 0,
output: 0,
reasoning: 0,
},
modelID: input.modelID,
providerID: input.providerID,
},
time: {
created: Date.now(),
},
sessionID: input.sessionID,
tool: {},
},
};
await updateMessage(next);
const result = streamText({
onStepFinish: async (step) => {
const assistant = next.metadata!.assistant!;
const usage = getUsage(step.usage, model.info);
assistant.cost = usage.cost;
assistant.tokens = usage.tokens;
await updateMessage(next);
},
abortSignal: abort.signal,
maxRetries: 6,
stopWhen: stepCountIs(1000),
messages: convertToModelMessages(msgs),
temperature: 0,
tools,
model: model.instance,
});
let text: Message.TextPart | undefined;
const reader = result.toUIMessageStream().getReader();
while (true) {
const result = await reader.read().catch((e) => {
if (e instanceof DOMException && e.name === "AbortError") {
return;
}
throw e;
});
if (!result) break;
const { done, value } = result;
if (done) break;
l.info("part", {
type: value.type,
});
switch (value.type) {
case "start":
break;
case "start-step":
text = undefined;
next.parts.push({
type: "step-start",
});
break;
case "text":
if (!text) {
text = value;
next.parts.push(value);
break;
}
text.text += value.text;
break;
case "tool-call":
next.parts.push({
type: "tool-invocation",
toolInvocation: {
state: "call",
...value,
// hack until zod v4
args: value.args as any,
},
});
break;
case "tool-result":
const match = next.parts.find(
(p) =>
p.type === "tool-invocation" &&
p.toolInvocation.toolCallId === value.toolCallId,
);
if (match && match.type === "tool-invocation") {
const { output, metadata } = value.result as any;
next.metadata!.tool[value.toolCallId] = metadata;
match.toolInvocation = {
...match.toolInvocation,
state: "result",
result: output,
};
}
break;
case "finish":
break;
case "finish-step":
break;
case "error":
log.error("error", value);
break;
default:
l.info("unhandled", {
type: value.type,
});
}
await updateMessage(next);
}
next.metadata!.time.completed = Date.now();
await updateMessage(next);
return next;
}
export async function summarize(input: {
sessionID: string;
providerID: string;
modelID: string;
}) {
using abort = lock(input.sessionID);
const msgs = await messages(input.sessionID);
const lastSummary = msgs.findLast(
(msg) => msg.metadata.assistant?.summary === true,
)?.id;
const filtered = msgs.filter(
(msg) => msg.role !== "system" && (!lastSummary || msg.id >= lastSummary),
);
const model = await LLM.findModel(input.providerID, input.modelID);
const next: Message.Info = {
id: Identifier.ascending("message"),
role: "assistant",
parts: [],
metadata: {
tool: {},
sessionID: input.sessionID,
assistant: {
summary: true,
cost: 0,
modelID: input.modelID,
providerID: input.providerID,
tokens: {
input: 0,
output: 0,
reasoning: 0,
},
},
time: {
created: Date.now(),
},
},
};
await updateMessage(next);
const result = await generateText({
abortSignal: abort.signal,
model: model.instance,
messages: convertToModelMessages([
{
role: "system",
parts: [
{
type: "text",
text: PROMPT_SUMMARIZE,
},
],
},
...filtered,
{
role: "user",
parts: [
{
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.",
},
],
},
]),
});
next.parts.push({
type: "text",
text: result.text,
});
const assistant = next.metadata!.assistant!;
const usage = getUsage(result.usage, model.info);
assistant.cost = usage.cost;
assistant.tokens = usage.tokens;
await updateMessage(next);
}
const pending = new Map<string, AbortController>();
function lock(sessionID: string) {
log.info("locking", { sessionID });
if (pending.has(sessionID)) throw new BusyError(sessionID);
const controller = new AbortController();
pending.set(sessionID, controller);
return {
signal: controller.signal,
[Symbol.dispose]() {
log.info("unlocking", { sessionID });
pending.delete(sessionID);
},
};
}
function getUsage(usage: LanguageModelUsage, model: Provider.Model) {
const tokens = {
input: usage.inputTokens ?? 0,
output: usage.outputTokens ?? 0,
reasoning: usage.reasoningTokens ?? 0,
};
return {
cost: new Decimal(0)
.add(new Decimal(tokens.input).mul(model.cost.input))
.add(new Decimal(tokens.output).mul(model.cost.output))
.toNumber(),
tokens,
};
}
export class BusyError extends Error {
constructor(public readonly sessionID: string) {
super(`Session ${sessionID} is busy`);
}
}
}
|