feat: Allow getting one chat at an index (#871)

# PR Checklist
- [ ] Have you checked if it works normally in all models? *Ignore this
if it doesn't use models.*
- [x] Have you checked if it works normally in all web, local, and node
hosted versions? If it doesn't, have you blocked it in those versions?
- [x] Have you added type definitions?

# Description

Getting one single chat at a specified index would help lighten Lua
scripts in certain scenarios such as "get the second last chat".

Currently I have to iterate (in `getFullChatMain`) the whole chat by
`getFullChat(id)` and then `fullChat[#fullChat - 1]`. With this PR, it
is simplified as `getChat(id, -2)`

Returns `nil` when no chat exists in the index.
This commit is contained in:
kwaroran
2025-05-25 18:22:05 +09:00
committed by GitHub

View File

@@ -109,6 +109,20 @@ export async function runLua(code:string, arg:{
}
return alertSelect(value)
})
luaEngine.global.set('getChatMain', (id:string, index:number) => {
const chat = luaEngineState.chat.message.at(index)
if(!chat){
return JSON.stringify(null)
}
const data = {
role: chat.role,
data: chat.data,
time: chat.time ?? 0
}
return JSON.stringify(data)
})
luaEngine.global.set('setChat', (id:string, index:number, value:string) => {
if(!LuaSafeIds.has(id)){
return
@@ -153,12 +167,14 @@ export async function runLua(code:string, arg:{
let roleData:'user'|'char' = role === 'user' ? 'user' : 'char'
luaEngineState.chat.message.splice(index, 0, {role: roleData, data: value})
})
luaEngine.global.set('getTokens', async (id:string, value:string) => {
if(!LuaSafeIds.has(id)){
return
}
return await tokenize(value)
})
luaEngine.global.set('getChatLength', (id:string) => {
return luaEngineState.chat.message.length
})
@@ -173,7 +189,7 @@ export async function runLua(code:string, arg:{
}))
return data
})
luaEngine.global.set('setFullChatMain', (id:string, value:string) => {
if(!LuaSafeIds.has(id)){
return
@@ -771,6 +787,10 @@ function luaCodeWarper(code:string){
return `
json = require 'json'
function getChat(id, index)
return json.decode(getChatMain(id, index))
end
function getFullChat(id)
return json.decode(getFullChatMain(id))
end