prompt.ts (1291B)
1 import { createOpencodeClient, type Part } from "@opencode-ai/sdk"; 2 import log from "./log.ts"; 3 4 interface PromptResult { 5 sessionId: string; 6 text: string; 7 } 8 9 interface PromptParams { 10 message: string; 11 sessionId?: string; 12 } 13 14 function logPart(part: Part): Part { 15 log("INFO", "Agent part", { part }); 16 return part; 17 } 18 19 export default async (params: PromptParams): Promise<PromptResult> => { 20 const baseUrl = process.env.OPENCODE_BASE_URL || undefined; 21 22 const { message, sessionId } = params; 23 24 log("INFO", "Prompting agent", { sessionId, baseUrl, message }); 25 26 const client = createOpencodeClient({ baseUrl }); 27 28 const id: string = await (async (): Promise<string> => { 29 if (sessionId) { 30 return sessionId; 31 } 32 33 log("INFO", "Creating opencode session"); 34 35 const sessionResult = await client.session.create(); 36 37 return sessionResult.data.id; 38 })(); 39 40 log("INFO", "Session connected", { sessionId: id }); 41 42 const result = await client.session.prompt({ 43 path: { id }, 44 body: { 45 parts: [{ type: "text", text: message }], 46 }, 47 }); 48 49 const text: string = result.data.parts 50 .map(logPart) 51 .filter((part) => part.type === "text") 52 .reduce((response: string, part) => response + " " + part.text, ""); 53 54 return { sessionId: id, text }; 55 };