2026-02-08 15:01:42 +09:00
|
|
|
import type { createOpencodeClient } from "@opencode-ai/sdk"
|
|
|
|
|
import type { MessageData, ResumeConfig } from "./types"
|
2026-05-13 13:25:01 +09:00
|
|
|
import { createInternalAgentContinuationTextPart, resolveInheritedPromptTools } from "../../shared"
|
2026-02-08 15:01:42 +09:00
|
|
|
|
|
|
|
|
const RECOVERY_RESUME_TEXT = "[session recovered - continuing previous task]"
|
|
|
|
|
|
|
|
|
|
type Client = ReturnType<typeof createOpencodeClient>
|
|
|
|
|
|
|
|
|
|
export function findLastUserMessage(messages: MessageData[]): MessageData | undefined {
|
|
|
|
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
|
|
|
if (messages[i].info?.role === "user") {
|
|
|
|
|
return messages[i]
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return undefined
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function extractResumeConfig(userMessage: MessageData | undefined, sessionID: string): ResumeConfig {
|
|
|
|
|
return {
|
|
|
|
|
sessionID,
|
|
|
|
|
agent: userMessage?.info?.agent,
|
|
|
|
|
model: userMessage?.info?.model,
|
2026-02-18 18:02:42 +09:00
|
|
|
tools: userMessage?.info?.tools,
|
2026-02-08 15:01:42 +09:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function resumeSession(client: Client, config: ResumeConfig): Promise<boolean> {
|
|
|
|
|
try {
|
2026-02-18 18:02:42 +09:00
|
|
|
const inheritedTools = resolveInheritedPromptTools(config.sessionID, config.tools)
|
2026-04-07 15:10:38 +09:00
|
|
|
const launchModel = config.model
|
|
|
|
|
? { providerID: config.model.providerID, modelID: config.model.modelID }
|
|
|
|
|
: undefined
|
|
|
|
|
const launchVariant = config.model?.variant
|
|
|
|
|
|
2026-02-08 15:01:42 +09:00
|
|
|
await client.session.promptAsync({
|
|
|
|
|
path: { id: config.sessionID },
|
|
|
|
|
body: {
|
2026-05-13 13:25:01 +09:00
|
|
|
parts: [createInternalAgentContinuationTextPart(RECOVERY_RESUME_TEXT)],
|
2026-02-08 15:01:42 +09:00
|
|
|
agent: config.agent,
|
2026-04-07 15:10:38 +09:00
|
|
|
...(launchModel ? { model: launchModel } : {}),
|
|
|
|
|
...(launchVariant ? { variant: launchVariant } : {}),
|
2026-02-18 18:02:42 +09:00
|
|
|
...(inheritedTools ? { tools: inheritedTools } : {}),
|
2026-02-08 15:01:42 +09:00
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
return true
|
|
|
|
|
} catch {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
}
|