import 'server-only' const AGENT_URL = process.env.OPS_AGENT_URL ?? 'http://127.0.0.1:3099' const AGENT_SECRET = process.env.OPS_AGENT_SECRET ?? '' export async function execAgent( commandKey: string, args: string[] = [], onChunk?: (chunk: string) => void, ): Promise { const response = await fetch(`${AGENT_URL}/agent/v1/exec`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${AGENT_SECRET}`, }, body: JSON.stringify({ command_key: commandKey, args }), cache: 'no-store', }) if (!response.ok) { const text = await response.text() throw new Error(`agent error ${response.status}: ${text}`) } const reader = response.body?.getReader() if (!reader) throw new Error('no response body') const decoder = new TextDecoder() let buffer = '' let output = '' while (true) { const { done, value } = await reader.read() if (done) break buffer += decoder.decode(value, { stream: true }) const lines = buffer.split('\n') buffer = lines.pop() ?? '' for (const line of lines) { if (line.startsWith('data:')) { const jsonStr = line.slice(5).trim() try { const parsed = JSON.parse(jsonStr) as { data?: string } if (parsed.data !== undefined) { output += parsed.data onChunk?.(parsed.data) } } catch { // skip malformed SSE data } } } } return output }