import { ref } from 'vue' import type { Agent } from '~~/types' export const useAgents = async () => { const { addTask, completeTask } = useTasks() const appState = useAppState() const fetchingAgents = ref(false); const agents: Ref = useState('agents', () => null); const activeAgent = computed(() => { if (agents.value === null) return; if (!appState.activeAgentId.value) return; const agent = agents.value.find(agent => agent.id === appState.activeAgentId.value); return agent; }); const refreshAgents = async () => { if (fetchingAgents.value) return; fetchingAgents.value = true; const { data, error } = await useFetch('/api/agents'); if (error.value) throw error; agents.value = data.value!; fetchingAgents.value = false; } if (agents.value === null) await refreshAgents(); const createAgent = async () => { const taskHandle = addTask() try { const agent = await $fetch('/api/agents', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'New Agent', systemPrompt: 'You are a helpful assistant.' }) }); if (agent === undefined) throw new Error('Failed to create agent'); if (agents.value === null) agents.value = []; agents.value.push(agent); completeTask(taskHandle) return agent; } catch (error) { console.error(error); completeTask(taskHandle) return; } } let debounceTimeout: NodeJS.Timeout | null = null; const updateAgent = async (id: string, data: Partial) => { if (agents.value === null) agents.value = []; // update the local state always agents.value = agents.value.map(agent => { if (agent.id === id) return { ...agent, ...data }; return agent; }); // falling edge debounce (when the user stops typing) if (debounceTimeout !== null) clearTimeout(debounceTimeout); debounceTimeout = setTimeout(async () => { const taskHandle = addTask() try { const agent = await $fetch(`/api/agents/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); if (agent === undefined) throw new Error('Failed to update agent'); const index = agents.value!.findIndex(agent => agent.id === id); if (index === -1) throw new Error('Agent not found'); if (agents.value![index] === null) throw new Error('Agent not found'); agents.value![index] = agent; completeTask(taskHandle) return agent; } catch (error) { console.error(error); completeTask(taskHandle) return; } }, 500); } return { agents, createAgent, activeAgent, updateAgent }; }