Add persistence and nick changes.

This commit is contained in:
JOLIMAITRE Matthieu 2025-05-28 19:01:20 +02:00
parent e357fabc30
commit ba61f6b0cf
5 changed files with 16 additions and 10 deletions

2
.gitignore vendored
View file

@ -1,2 +1,2 @@
/target
/history
/history.json

View file

@ -22,8 +22,8 @@ $ ./src/kub.ts
## TODO
- [ ] Auto update.
- [ ] Colored chat.
- [ ] Persistent chat.
- [ ] System messages.
- Change of days.
- [ ] Tools.

View file

@ -1 +0,0 @@
{"messages":[]}

View file

@ -7,9 +7,10 @@ export class History {
private limit: number,
) {}
public push(value: Message) {
public async push(value: Message) {
this.messages.push(value)
while (this.messages.length > this.limit) this.messages.splice(0, 1)
await this.save()
}
public static async load(path: string, limit: number) {
@ -30,6 +31,6 @@ export class History {
}
private async save() {
await Deno.writeTextFile(this.path, JSON.stringify({ messages: this.messages }))
await Deno.writeTextFile(this.path, JSON.stringify({ messages: this.messages }, null, 4))
}
}

View file

@ -24,8 +24,14 @@ export async function session(conn: Deno.TcpConn, name: string, history: History
for await (const line of lines) {
if (line === "") continue
if (line.length > 10_000) return
console.log("prompted '", line, "' by ", conn.remoteAddr.hostname)
await write_encoded(conn, "\n< ")
console.log("user", conn.remoteAddr.hostname, "promoted", line)
if (line.startsWith("/nick ")) {
name = line.slice("/nick ".length)
console.log("Changed name of", conn.remoteAddr.hostname, "to", name)
await write_encoded(conn, "\n> ")
continue
}
await write_encoded(conn, "\n[kub] ")
const user_message = make_message(name, line)
const response_parts = await get_response_parts(history, user_message)
let content = "", role = "assistant"
@ -34,9 +40,9 @@ export async function session(conn: Deno.TcpConn, name: string, history: History
content += part.message.content
role = part.message.role
}
await write_encoded(conn, "\n\n>")
history.push(user_message)
history.push({ role, content })
await write_encoded(conn, "\n\n> ")
await history.push(user_message)
await history.push({ role, content })
}
}