import"./DrKWWDpL.js";import{t as e}from"./DYP3EJMY.js";import{N as t,k as n,v as r,w as i}from"./DsanjglN.js";import{Lt as a,Rt as o}from"./CvaH7m0y.js";import{i as s}from"./CG84LPq-.js";e();async function c(e,t,n){let r=await s(n),c=await r.select().from(o).where(i(o.id,e)).get();if(!c)return null;let l={status:t.status};if(t.taskId!==void 0&&(l.taskId=t.taskId),t.status===`active`&&(l.lastHeartbeat=new Date().toISOString()),(t.status===`error`||t.status===`crashed`)&&(l.errorCount=c.errorCount+1,t.error)){let n=p(Error(t.error));await r.insert(a).values({agentId:e,errorType:n,message:t.error,occurredAt:new Date().toISOString()})}return t.status===`stopped`&&(l.stoppedAt=new Date().toISOString()),await r.update(o).set(l).where(i(o.id,e)),{...c,...l}}async function l(e,t){let a=await s(t),c=[];if(e?.status){let t=Array.isArray(e.status)?e.status:[e.status];c.push(n(o.status,t))}if(e?.agentType){let t=Array.isArray(e.agentType)?e.agentType:[e.agentType];c.push(n(o.agentType,t))}return e?.sessionId&&c.push(i(o.sessionId,e.sessionId)),e?.parentAgentId&&c.push(i(o.parentAgentId,e.parentAgentId)),c.length===0?a.select().from(o).all():a.select().from(o).where(r(...c)).all()}async function u(e,t){return await(await s(t)).select().from(o).where(i(o.id,e)).get()??null}var d=[/timeout/i,/ECONNREFUSED/,/ECONNRESET/,/EPIPE/,/ETIMEDOUT/,/rate.?limit/i,/429/,/503/,/502/,/SQLITE_BUSY/i,/database is locked/i,/temporarily unavailable/i,/too many requests/i,/network/i,/socket hang up/i],f=[/permission denied/i,/EACCES/,/authentication/i,/unauthorized/i,/401/,/403/,/404/,/not found/i,/invalid.*token/i,/SQLITE_CONSTRAINT/i,/syntax error/i,/type error/i,/reference error/i];function p(e){let t=e instanceof Error?e.message:String(e);for(let e of d)if(e.test(t))return`retriable`;for(let e of f)if(e.test(t))return`permanent`;return`unknown`}async function m(e,t){return(await s(t)).select().from(a).where(i(a.agentId,e)).all()}async function h(e=3e4,i){let a=await s(i),c=new Date(Date.now()-e).toISOString();return a.select().from(o).where(r(n(o.status,[`active`,`idle`,`starting`]),t(o.lastHeartbeat,c))).all()}async function g(e,t,n){return c(e,{status:`crashed`,error:t??`Heartbeat timeout — agent presumed crashed`},n)}export{l as a,u as i,p as n,g as o,m as r,c as s,h as t};