( agent: CompleteAgent, code: string )
| 71 | |
| 72 | // Create or update an agent |
| 73 | export async function saveAgent( |
| 74 | agent: CompleteAgent, |
| 75 | code: string |
| 76 | ): Promise<CompleteAgent> { |
| 77 | // Validate agent ID (letters, numbers, underscores only) |
| 78 | if (!agent.id.match(/^[a-zA-Z0-9_]+$/)) { |
| 79 | throw new Error('Invalid agent ID. Use only letters, numbers, and underscores.'); |
| 80 | } |
| 81 | |
| 82 | const db = await openDB(); |
| 83 | |
| 84 | // Start a transaction to save all related data |
| 85 | const tx = db.transaction([AGENT_STORE, CONFIG_STORE, CODE_STORE], 'readwrite'); |
| 86 | |
| 87 | // Save agent metadata - extract just the metadata fields |
| 88 | const agentMetadata = { |
| 89 | id: agent.id, |
| 90 | name: agent.name, |
| 91 | description: agent.description |
| 92 | }; |
| 93 | |
| 94 | const agentStore = tx.objectStore(AGENT_STORE); |
| 95 | await new Promise<void>((resolve, reject) => { |
| 96 | const request = agentStore.put(agentMetadata); |
| 97 | request.onsuccess = () => resolve(); |
| 98 | request.onerror = () => reject(request.error); |
| 99 | }); |
| 100 | |
| 101 | // Save agent config - extract just the config fields |
| 102 | const agentConfig = { |
| 103 | id: agent.id, |
| 104 | model_name: agent.model_name, |
| 105 | system_prompt: agent.system_prompt, |
| 106 | loop_interval_seconds: agent.loop_interval_seconds, |
| 107 | only_on_significant_change: agent.only_on_significant_change |
| 108 | }; |
| 109 | |
| 110 | const configStore = tx.objectStore(CONFIG_STORE); |
| 111 | await new Promise<void>((resolve, reject) => { |
| 112 | const request = configStore.put(agentConfig); |
| 113 | request.onsuccess = () => resolve(); |
| 114 | request.onerror = () => reject(request.error); |
| 115 | }); |
| 116 | |
| 117 | // Save agent code |
| 118 | const codeStore = tx.objectStore(CODE_STORE); |
| 119 | await new Promise<void>((resolve, reject) => { |
| 120 | const request = codeStore.put({ |
| 121 | id: agent.id, |
| 122 | code |
| 123 | }); |
| 124 | request.onsuccess = () => resolve(); |
| 125 | request.onerror = () => reject(request.error); |
| 126 | }); |
| 127 | |
| 128 | // Complete the transaction |
| 129 | await new Promise<void>((resolve, reject) => { |
| 130 | tx.oncomplete = () => resolve(); |
no test coverage detected