(runtimeId: string, workspaceId?: string)
| 243 | } |
| 244 | |
| 245 | export function claimNextQueuedTaskForRuntimeSync(runtimeId: string, workspaceId?: string): QueuedTaskRecord | null { |
| 246 | const db = getDatabase(); |
| 247 | const now = new Date().toISOString(); |
| 248 | let claimedId: string | null = null; |
| 249 | let fallbackReason: string | undefined; |
| 250 | |
| 251 | db.exec("BEGIN"); |
| 252 | try { |
| 253 | let row = selectQueuedTaskForRuntime(db, runtimeId, workspaceId); |
| 254 | if (!row) { |
| 255 | const fallback = selectFallbackQueuedTaskForRuntime(db, runtimeId, workspaceId); |
| 256 | if (fallback) { |
| 257 | row = fallback.row; |
| 258 | fallbackReason = fallback.reason; |
| 259 | db.prepare( |
| 260 | `UPDATE agent_task_queue |
| 261 | SET runtime_id = ?, |
| 262 | updated_at = ? |
| 263 | WHERE id = ? AND status = 'queued'`, |
| 264 | ).run(runtimeId, now, row.id); |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | if (row && typeof row.id === "string") { |
| 269 | db.prepare( |
| 270 | `UPDATE agent_task_queue |
| 271 | SET status = 'claimed', |
| 272 | claimed_at = ?, |
| 273 | updated_at = ? |
| 274 | WHERE id = ? AND status = 'queued'`, |
| 275 | ).run(now, now, row.id); |
| 276 | claimedId = row.id; |
| 277 | } |
| 278 | db.exec("COMMIT"); |
| 279 | } catch (error) { |
| 280 | db.exec("ROLLBACK"); |
| 281 | throw error; |
| 282 | } |
| 283 | |
| 284 | const task = claimedId ? readQueuedTaskSync(claimedId) : null; |
| 285 | if (task) { |
| 286 | const runtime = readAgentRuntimeSync(task.runtimeId); |
| 287 | const providerSession = chooseProviderSessionForTaskSync({ task }); |
| 288 | const attempt = runtime && task.routerSessionId |
| 289 | ? createAgentTaskAttemptSync({ |
| 290 | workspaceId: task.workspaceId, |
| 291 | taskQueueId: task.id, |
| 292 | routerSessionId: task.routerSessionId, |
| 293 | runtimeId: task.runtimeId, |
| 294 | provider: runtime.provider, |
| 295 | providerSessionId: providerSession?.providerSessionId, |
| 296 | status: "claimed", |
| 297 | metadata: { |
| 298 | routingMode: providerSession ? "same_provider_resume" : fallbackReason ? "cold_rebuild_fallback" : "cold_rebuild", |
| 299 | fallbackReason, |
| 300 | previousRuntimeId: fallbackReason ? readStringFromTaskInput(task.inputJson, "__previousRuntimeId") : undefined, |
| 301 | }, |
| 302 | }) |
no test coverage detected