feat: add SDK read paths for session-recovery parts/messages readers

This commit is contained in:
YeonGyu-Kim
2026-02-15 14:56:50 +09:00
parent 4574544849
commit a18ec856c6
3 changed files with 101 additions and 0 deletions
@@ -1,9 +1,42 @@
import { existsSync, readdirSync, readFileSync } from "node:fs"
import { join } from "node:path"
import type { PluginInput } from "@opencode-ai/plugin"
import type { StoredMessageMeta } from "../types"
import { getMessageDir } from "./message-dir"
import { isSqliteBackend } from "../../../shared"
type OpencodeClient = PluginInput["client"]
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null
}
function normalizeSDKMessage(
sessionID: string,
value: unknown
): StoredMessageMeta | null {
if (!isRecord(value)) return null
if (typeof value.id !== "string") return null
const roleValue = value.role
const role: StoredMessageMeta["role"] = roleValue === "assistant" ? "assistant" : "user"
const created =
isRecord(value.time) && typeof value.time.created === "number"
? value.time.created
: 0
return {
id: value.id,
sessionID,
role,
time: { created },
}
}
export function readMessages(sessionID: string): StoredMessageMeta[] {
if (isSqliteBackend()) return []
const messageDir = getMessageDir(sessionID)
if (!messageDir || !existsSync(messageDir)) return []
@@ -25,3 +58,27 @@ export function readMessages(sessionID: string): StoredMessageMeta[] {
return a.id.localeCompare(b.id)
})
}
export async function readMessagesFromSDK(
client: OpencodeClient,
sessionID: string
): Promise<StoredMessageMeta[]> {
try {
const response = await client.session.messages({ path: { id: sessionID } })
const data: unknown = response.data
if (!Array.isArray(data)) return []
const messages = data
.map((msg): StoredMessageMeta | null => normalizeSDKMessage(sessionID, msg))
.filter((msg): msg is StoredMessageMeta => msg !== null)
return messages.sort((a, b) => {
const aTime = a.time?.created ?? 0
const bTime = b.time?.created ?? 0
if (aTime !== bTime) return aTime - bTime
return a.id.localeCompare(b.id)
})
} catch {
return []
}
}