"use strict";exports.id=5901,exports.ids=[5901],exports.modules={35901:(a,b,c)=>{c.d(b,{Wl:()=>C,jk:()=>x});var d=c(29021),e=c.n(d),f=c(33873),g=c.n(f),h=c(45903);let i=Number(process.env.REQUEST_ERROR_BODY_SNIPPET_CHARS||4096);function j(a){return String(a??"").trim()}function k(a){return j(a).toLowerCase()}function l(a,b=null){let c=Number(a);return Number.isFinite(c)?c:b}function m(a,b=1e3){let c=j(a).replace(/\s+/g," ");return c?c.length>b?`${c.slice(0,Math.max(0,b-1))}…`:c:""}function n(){return g().join(process.env.DATA_DIR||"/var/lib/bluerouter","logs","promptLogs.sqlite")}async function o(){let a=(0,h.I6)(await (0,h.L7)());return a.sqlitePath||(a.sqlitePath=n()),a}async function p(a){e().mkdirSync(g().dirname(a),{recursive:!0});try{let b=await Promise.resolve().then(c.t.bind(c,87550,23)),d=new(b.default||b)(a);return d.pragma("journal_mode = WAL"),d.pragma("busy_timeout = 5000"),{type:"sqlite",all:(a,b=[])=>d.prepare(a).all(...b),get:(a,b=[])=>d.prepare(a).get(...b),run:(a,b=[])=>d.prepare(a).run(...b),exec:a=>d.exec(a),close:()=>d.close()}}catch{let b=new(await Promise.resolve().then(c.t.bind(c,80099,23))).DatabaseSync(a);return b.exec("PRAGMA journal_mode = WAL"),b.exec("PRAGMA busy_timeout = 5000"),{type:"sqlite",all:(a,c=[])=>b.prepare(a).all(...c),get:(a,c=[])=>b.prepare(a).get(...c),run:(a,c=[])=>b.prepare(a).run(...c),exec:a=>b.exec(a),close:()=>b.close()}}}async function q(a){let b=new(await Promise.resolve().then(c.bind(c,64939))).Client({host:a.host,port:Number(a.port||5432),database:a.database,user:a.username,password:a.password,ssl:!!a.ssl&&{rejectUnauthorized:!1}});return await b.connect(),{type:"postgres",query:async(a,c=[])=>(await b.query(a,c)).rows,queryOne:async(a,c=[])=>(await b.query(a,c)).rows[0]||null,exec:async a=>{await b.query(a)},close:async()=>{await b.end()}}}async function r(a){let b=await c.e(8491).then(c.t.bind(c,38491,19)),d=await b.createConnection({host:a.host,port:Number(a.port||3306),database:a.database,user:a.username,password:a.password,ssl:a.ssl?{}:void 0,multipleStatements:!0,dateStrings:!0});return{type:"mysql",query:async(a,b=[])=>(await d.query(a,b))[0],queryOne:async(a,b=[])=>((await d.query(a,b))[0]||[])[0]||null,exec:async a=>{await d.query(a)},close:async()=>{await d.end()}}}async function s(a){if("sqlite"===a.type)return p(a.sqlitePath||n());if("postgres"===a.type)return q(a);if("mysql"===a.type)return r(a);throw Error(`Unsupported prompt log database type: ${a.type}`)}async function t(a){"sqlite"===a.type?a.exec(`
    CREATE TABLE IF NOT EXISTS request_error_events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      created_at TEXT NOT NULL,
      request_id TEXT,
      attempt_index INTEGER DEFAULT 0,
      provider TEXT,
      model TEXT,
      connection_id TEXT,
      account_name TEXT,
      endpoint TEXT,
      gateway_status_code INTEGER,
      upstream_status_code INTEGER,
      status_class TEXT,
      error_source TEXT,
      error_type TEXT,
      error_code TEXT,
      error_message_short TEXT,
      upstream_error_body_snippet TEXT,
      upstream_request_id TEXT,
      latency_ms INTEGER DEFAULT 0,
      api_key_id TEXT,
      api_key_fingerprint TEXT,
      client_ip TEXT,
      client_ip_normalized TEXT,
      source_tool TEXT,
      source_tool_label TEXT,
      session_id TEXT,
      meta_json TEXT
    );
    CREATE INDEX IF NOT EXISTS idx_ree_created_at ON request_error_events(created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_request_id ON request_error_events(request_id);
    CREATE INDEX IF NOT EXISTS idx_ree_gateway_status ON request_error_events(gateway_status_code, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_upstream_status ON request_error_events(upstream_status_code, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_error_type ON request_error_events(error_type, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_error_code ON request_error_events(error_code, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_error_source ON request_error_events(error_source, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_provider_model ON request_error_events(provider, model, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_connection ON request_error_events(connection_id, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_api_key ON request_error_events(api_key_id, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_api_fp ON request_error_events(api_key_fingerprint, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_client_ip ON request_error_events(client_ip_normalized, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_source_tool ON request_error_events(source_tool, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_session ON request_error_events(session_id, created_at DESC);
  `):"postgres"===a.type?await a.exec(`
    CREATE TABLE IF NOT EXISTS request_error_events (
      id BIGSERIAL PRIMARY KEY,
      created_at TIMESTAMPTZ NOT NULL,
      request_id TEXT,
      attempt_index INTEGER DEFAULT 0,
      provider TEXT,
      model TEXT,
      connection_id TEXT,
      account_name TEXT,
      endpoint TEXT,
      gateway_status_code INTEGER,
      upstream_status_code INTEGER,
      status_class TEXT,
      error_source TEXT,
      error_type TEXT,
      error_code TEXT,
      error_message_short TEXT,
      upstream_error_body_snippet TEXT,
      upstream_request_id TEXT,
      latency_ms INTEGER DEFAULT 0,
      api_key_id TEXT,
      api_key_fingerprint TEXT,
      client_ip TEXT,
      client_ip_normalized TEXT,
      source_tool TEXT,
      source_tool_label TEXT,
      session_id TEXT,
      meta_json JSONB
    );
    CREATE INDEX IF NOT EXISTS idx_ree_created_at ON request_error_events(created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_request_id ON request_error_events(request_id);
    CREATE INDEX IF NOT EXISTS idx_ree_gateway_status ON request_error_events(gateway_status_code, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_upstream_status ON request_error_events(upstream_status_code, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_error_type ON request_error_events(error_type, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_error_code ON request_error_events(error_code, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_error_source ON request_error_events(error_source, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_provider_model ON request_error_events(provider, model, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_connection ON request_error_events(connection_id, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_api_key ON request_error_events(api_key_id, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_api_fp ON request_error_events(api_key_fingerprint, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_client_ip ON request_error_events(client_ip_normalized, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_source_tool ON request_error_events(source_tool, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_ree_session ON request_error_events(session_id, created_at DESC);
  `):"mysql"===a.type&&await a.exec(`
    CREATE TABLE IF NOT EXISTS request_error_events (
      id BIGINT AUTO_INCREMENT PRIMARY KEY,
      created_at DATETIME(3) NOT NULL,
      request_id VARCHAR(80),
      attempt_index INT DEFAULT 0,
      provider VARCHAR(120),
      model VARCHAR(255),
      connection_id VARCHAR(120),
      account_name VARCHAR(255),
      endpoint TEXT,
      gateway_status_code INT,
      upstream_status_code INT,
      status_class VARCHAR(32),
      error_source VARCHAR(80),
      error_type VARCHAR(120),
      error_code VARCHAR(160),
      error_message_short TEXT,
      upstream_error_body_snippet TEXT,
      upstream_request_id VARCHAR(255),
      latency_ms INT DEFAULT 0,
      api_key_id VARCHAR(120),
      api_key_fingerprint VARCHAR(120),
      client_ip VARCHAR(64),
      client_ip_normalized VARCHAR(64),
      source_tool VARCHAR(80),
      source_tool_label VARCHAR(120),
      session_id VARCHAR(255),
      meta_json JSON,
      INDEX idx_ree_created_at (created_at),
      INDEX idx_ree_request_id (request_id),
      INDEX idx_ree_gateway_status (gateway_status_code, created_at),
      INDEX idx_ree_upstream_status (upstream_status_code, created_at),
      INDEX idx_ree_error_type (error_type, created_at),
      INDEX idx_ree_error_code (error_code, created_at),
      INDEX idx_ree_error_source (error_source, created_at),
      INDEX idx_ree_provider_model (provider, model, created_at),
      INDEX idx_ree_connection (connection_id, created_at),
      INDEX idx_ree_api_key (api_key_id, created_at),
      INDEX idx_ree_api_fp (api_key_fingerprint, created_at),
      INDEX idx_ree_client_ip (client_ip_normalized, created_at),
      INDEX idx_ree_source_tool (source_tool, created_at),
      INDEX idx_ree_session (session_id, created_at)
    ) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
  `)}function u(a){let b=Number(a);return Number.isFinite(b)&&b>=200&&b<300}function v({statusCode:a,errorSource:b,errorCode:c,message:d}){let e=k(`${c} ${d}`),f=k(b),g=Number(a);return e.includes("context")||e.includes("maximum")||e.includes("token")||e.includes("too long")||413===g?"context_length_exceeded":401===g||e.includes("unauthorized")||e.includes("invalid api key")?"auth_error":403===g||e.includes("forbidden")||e.includes("not allowed")?"forbidden":429===g||e.includes("rate limit")?"rate_limit":e.includes("quota")?"quota_exceeded":e.includes("model_not_found")||e.includes("model not found")||e.includes("invalid model")?"model_not_found":e.includes("timeout")||f.includes("timeout")?"timeout":e.includes("abort")||499===g?"client_abort":e.includes("invalid json")?"invalid_json":e.includes("invalid sse")?"invalid_sse":f.includes("network")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("etimedout")||e.includes("socket hang up")||e.includes("fetch failed")?"network_error":g>=500?"provider_unavailable":g>=400?"invalid_request":j(c)||"unknown_error"}function w(a={}){return{disabled:!0,total:0,summary:{total:0,serverImpacting:0,gateway:0,upstream:0,client:0,rateLimit:0,unknown:0,serverImpactingRate:0,clientRate:0,rateLimitRate:0},topErrors:[],topServerErrors:[],topClientErrors:[],topRateLimitErrors:[],byFaultOwner:[],byStatusCode:[],byStatusClass:[],byErrorType:[],byErrorSource:[],byProvider:[],byModel:[],byClientIp:[],bySourceTool:[],recent:[],...a}}async function x(a={}){let b;try{if(!(b=await o()).enabled||!1===b.logErrors)return{skipped:!0,reason:"prompt_log_db_disabled"};let e=await s(b);try{var c,d;let b,f;await t(e);let g=function(a={}){let b,c,d=l(a.gatewayStatusCode??a.statusCode,null),e=l(a.upstreamStatusCode,null),f=m(a.errorMessageShort||a.errorMessage||a.message||a.error?.message||a.error||""),g=j(a.errorCode)||j(a.code)||v({statusCode:e||d,errorSource:a.errorSource,message:f}),h=j(a.errorType)||v({statusCode:e||d,errorSource:a.errorSource,errorCode:g,message:f}),n=j(a.clientIp||a.sourceIp),o=a.meta&&"object"==typeof a.meta?a.meta:{};return{createdAt:a.createdAt||a.timestamp||new Date().toISOString(),requestId:j(a.requestId||o.requestId),attemptIndex:l(a.attemptIndex,0)||0,provider:j(a.provider)||"unknown",model:j(a.model)||"unknown",connectionId:j(a.connectionId),accountName:j(a.accountName||a.connectionName),endpoint:j(a.endpoint),gatewayStatusCode:d,upstreamStatusCode:e,statusClass:j(a.statusClass)||function(a,b,c){let d=l(b,l(a,null)),e=k(c);if(e.includes("timeout"))return"timeout";if(e.includes("network"))return"network";if(Number.isFinite(d)){if(d>=500)return"5xx";if(d>=400)return"4xx";if(d>=300)return"3xx";if(d>=200)return"2xx"}return e||"error"}(d,e,a.errorSource),errorSource:j(a.errorSource)||"unknown_error_source",errorType:h,errorCode:g,errorMessageShort:f,upstreamErrorBodySnippet:function(a,b=i){if(null==a)return"";let c="";if("string"==typeof a)c=a;else try{c=JSON.stringify(a)}catch{c=String(a)}return m(c,b)}(a.upstreamErrorBodySnippet??a.upstreamBody??a.responseBody??a.providerResponseBody),upstreamRequestId:j(a.upstreamRequestId),latencyMs:l(a.latencyMs,0)||0,apiKeyId:j(a.apiKeyId),apiKeyFingerprint:j(a.apiKeyFingerprint)||((b=j(a.apiKey))?b.length<=12?b:`${b.slice(0,8)}...${b.slice(-4)}`:"local-no-key"),clientIp:n,clientIpNormalized:j(a.clientIpNormalized)||((c=j(n))?c.split(",")[0].trim().replace(/^::ffff:/,""):""),sourceTool:j(a.sourceTool||o.sourceTool),sourceToolLabel:j(a.sourceToolLabel||o.sourceToolLabel),sessionId:j(a.sessionId||o.sessionId),metaJson:JSON.stringify({...o,storedBy:"request_error_events"})}}(a);if(!g||u(g.upstreamStatusCode)||u(g.gatewayStatusCode)||(d=g.statusClass,(f=k(d))&&(["pending","running","in_progress","queued","processing"].includes(k(f))||["2xx","ok","success","succeeded","complete","completed","done","200"].includes(f)||/^(?:2\d\d|ok|success|succeeded|complete|completed|done)(?:\b|[\s_-]|$)/.test(f))))return{skipped:!0,reason:"non_error_or_pending_event"};let h=(c=e.type,b=["created_at","request_id","attempt_index","provider","model","connection_id","account_name","endpoint","gateway_status_code","upstream_status_code","status_class","error_source","error_type","error_code","error_message_short","upstream_error_body_snippet","upstream_request_id","latency_ms","api_key_id","api_key_fingerprint","client_ip","client_ip_normalized","source_tool","source_tool_label","session_id","meta_json"],"postgres"===c?`INSERT INTO request_error_events (${b.join(", ")}) VALUES (${b.map((a,b)=>`$${b+1}`).join(", ")})`:`INSERT INTO request_error_events (${b.join(", ")}) VALUES (${b.map(()=>"?").join(", ")})`),n=[g.createdAt,g.requestId,g.attemptIndex,g.provider,g.model,g.connectionId,g.accountName,g.endpoint,g.gatewayStatusCode,g.upstreamStatusCode,g.statusClass,g.errorSource,g.errorType,g.errorCode,g.errorMessageShort,g.upstreamErrorBodySnippet,g.upstreamRequestId,g.latencyMs,g.apiKeyId,g.apiKeyFingerprint,g.clientIp,g.clientIpNormalized,g.sourceTool,g.sourceToolLabel,g.sessionId,g.metaJson];return"sqlite"===e.type?e.run(h,n):await e.query(h,n),{ok:!0,event:g}}finally{await e.close()}}catch(a){return console.warn(`[RequestErrorEvents] save failed: ${a?.message||a}`),{ok:!1,error:a?.message||String(a)}}}function y(a,b,c){let d=c.map(a=>`'${a.replace(/'/g,"''")}'`).join(", "),e=`${b} IN (${d})`;return a?`${a} AND ${e}`:`WHERE ${e}`}function z(a={},b={}){let c=l(a.requests,0)||0;return{key:j(a.key)||"unknown",label:j(a.label||a.key)||"unknown",requests:c,success:0,errors:c,errorRate:+!!c,promptTokens:0,completionTokens:0,totalTokens:0,cost:0,lastSeen:a.lastSeen||a.last_seen||"",...b}}async function A(a,b,c=[]){return"sqlite"===a.type?a.all(b,c):a.query(b,c)}async function B(a,b,c=[]){return"sqlite"===a.type?a.get(b,c):a.queryOne(b,c)}async function C(a={}){let b=await o();if(!b.enabled)return w({disabled:!0});let c=await s(b);try{var d;let b,e,f,g,h,i;await t(c);let k=function(a={},b="sqlite"){let c=[],d=[],e=a=>(d.push(a),"postgres"===b)?`$${d.length}`:"?",f="postgres"===b?"ILIKE":"LIKE";if(c.push("(COALESCE(upstream_status_code, gateway_status_code) IS NULL OR COALESCE(upstream_status_code, gateway_status_code) < 200 OR COALESCE(upstream_status_code, gateway_status_code) >= 300)"),c.push("(status_class IS NULL OR (lower(status_class) NOT IN ('2xx','ok','success','succeeded','complete','completed','done','200','pending','running','in_progress','queued','processing') AND lower(status_class) NOT LIKE '2__%' AND lower(status_class) NOT LIKE 'ok%' AND lower(status_class) NOT LIKE 'success%' AND lower(status_class) NOT LIKE 'succeeded%' AND lower(status_class) NOT LIKE 'complete%' AND lower(status_class) NOT LIKE 'completed%'))"),a.dateFrom&&c.push(`created_at >= ${e(a.dateFrom)}`),a.dateTo&&c.push(`created_at <= ${e(a.dateTo)}`),a.provider&&c.push(`provider = ${e(a.provider)}`),a.model&&c.push(`model = ${e(a.model)}`),a.connectionId&&c.push(`connection_id = ${e(a.connectionId)}`),a.clientIp&&c.push(`client_ip_normalized ${f} ${e(`%${a.clientIp}%`)}`),a.sourceTool&&c.push(`(source_tool ${f} ${e(`%${a.sourceTool}%`)} OR source_tool_label ${f} ${e(`%${a.sourceTool}%`)})`),a.sessionId&&c.push(`session_id = ${e(a.sessionId)}`),a.endpoint&&c.push(`endpoint ${f} ${e(`%${a.endpoint}%`)}`),a.statusCode&&c.push(`(gateway_status_code = ${e(Number(a.statusCode))} OR upstream_status_code = ${e(Number(a.statusCode))})`),a.status){let b=j(a.status);/^\d+$/.test(b)?c.push(`(gateway_status_code = ${e(Number(b))} OR upstream_status_code = ${e(Number(b))})`):c.push(`(status_class = ${e(b)} OR error_type = ${e(b)} OR error_code = ${e(b)})`)}if(a.errorType&&c.push(`error_type = ${e(a.errorType)}`),a.errorCode&&c.push(`error_code = ${e(a.errorCode)}`),a.errorSource&&c.push(`error_source = ${e(a.errorSource)}`),a.apiKey){let b=`%${a.apiKey}%`;c.push(`(api_key_id ${f} ${e(b)} OR api_key_fingerprint ${f} ${e(b)})`)}if(a.keyword){let b=`%${a.keyword}%`;c.push(`(error_message_short ${f} ${e(b)} OR upstream_error_body_snippet ${f} ${e(b)} OR request_id ${f} ${e(b)} OR error_code ${f} ${e(b)})`)}return{clause:c.length?`WHERE ${c.join(" AND ")}`:"",params:d}}(a,c.type),m=await B(c,`SELECT COUNT(*) AS total FROM request_error_events ${k.clause}`,k.params),n=l(m?.total,0)||0,o="postgres"===c.type?`$${k.params.length+1}`:"?",p=[...k.params,100],q=(d=c.type,b="mysql"===d?"CHAR":"TEXT",`COALESCE(CAST(upstream_status_code AS ${b}), CAST(gateway_status_code AS ${b}), status_class, 'error')`),r=(c.type,e="COALESCE(upstream_status_code, gateway_status_code)",f="lower(COALESCE(error_type, ''))",g="lower(COALESCE(error_code, ''))",h="lower(COALESCE(error_source, ''))",i="lower(COALESCE(error_message_short, ''))",`CASE
    WHEN (${e} BETWEEN 200 AND 299 OR lower(COALESCE(status_class, '')) IN ('2xx','ok','success','succeeded','complete','completed','done','200')) THEN 'non_error'
    WHEN (${e} = 429 OR ${f} IN ('rate_limit','quota_exceeded') OR ${g} IN ('rate_limit','quota_exceeded') OR ${i} LIKE '%rate limit%' OR ${i} LIKE '%quota%') THEN 'rate_limit'
    WHEN (${f} = 'client_abort' OR ${h} = 'client_abort' OR ${e} = 499) THEN 'client'
    WHEN (COALESCE(upstream_status_code, 0) >= 500) THEN 'upstream'
    WHEN (${f} IN ('provider_unavailable','timeout','network_error','invalid_sse') OR ${h} LIKE '%provider%' OR ${h} LIKE '%upstream%' OR ${h} LIKE '%network%' OR ${h} LIKE '%timeout%' OR ${i} LIKE '%econnreset%' OR ${i} LIKE '%econnrefused%' OR ${i} LIKE '%etimedout%' OR ${i} LIKE '%socket hang up%' OR ${i} LIKE '%fetch failed%') THEN 'upstream'
    WHEN (${f} IN ('invalid_request','invalid_json','model_not_found','context_length_exceeded','auth_error','forbidden') OR ${g} IN ('bad_request','invalid_request','invalid_json','model_not_found','context_length_exceeded','auth_error','forbidden','not_found') OR ${e} IN (400,401,403,404,405,406,413,415,422)) THEN 'client'
    WHEN (COALESCE(gateway_status_code, 0) >= 500 OR ${f} LIKE 'gateway%' OR (${h} LIKE 'gateway%' AND ${h} <> 'gateway_validation')) THEN 'gateway'
    ELSE 'unknown'
  END`),s="mysql"===c.type?`CONCAT(${r}, '|', ${q}, '|', COALESCE(NULLIF(error_type, ''), 'unknown_error'), '|', COALESCE(NULLIF(provider, ''), 'unknown'), '|', COALESCE(NULLIF(model, ''), 'unknown'), '|', COALESCE(NULLIF(endpoint, ''), 'unknown'))`:`${r} || '|' || ${q} || '|' || COALESCE(NULLIF(error_type, ''), 'unknown_error') || '|' || COALESCE(NULLIF(provider, ''), 'unknown') || '|' || COALESCE(NULLIF(model, ''), 'unknown') || '|' || COALESCE(NULLIF(endpoint, ''), 'unknown')`,u=a=>`SELECT
         ${s} AS key,
         ${r} AS faultOwner,
         ${q} AS status,
         COALESCE(NULLIF(error_type, ''), 'unknown_error') AS errorType,
         COALESCE(NULLIF(error_code, ''), 'unknown_error') AS errorCode,
         COALESCE(NULLIF(error_source, ''), 'unknown') AS errorSource,
         COALESCE(NULLIF(provider, ''), 'unknown') AS provider,
         COALESCE(NULLIF(model, ''), 'unknown') AS model,
         COALESCE(NULLIF(endpoint, ''), 'unknown') AS endpoint,
         COALESCE(NULLIF(api_key_fingerprint, ''), 'local-no-key') AS apiKey,
         COUNT(*) AS requests,
         MAX(created_at) AS lastSeen,
         MAX(error_message_short) AS sampleMessage
       FROM request_error_events
       ${a}
       GROUP BY ${r}, ${q}, COALESCE(NULLIF(error_type, ''), 'unknown_error'), COALESCE(NULLIF(error_code, ''), 'unknown_error'), COALESCE(NULLIF(error_source, ''), 'unknown'), COALESCE(NULLIF(provider, ''), 'unknown'), COALESCE(NULLIF(model, ''), 'unknown'), COALESCE(NULLIF(endpoint, ''), 'unknown'), COALESCE(NULLIF(api_key_fingerprint, ''), 'local-no-key')
       ORDER BY requests DESC, lastSeen DESC
       LIMIT ${o}`,v=(a=[])=>a.map(a=>z(a,{label:`${a.faultOwner||"unknown"} \xb7 ${a.status||"error"} \xb7 ${a.errorType||a.errorCode||"unknown_error"}`,faultOwner:a.faultOwner||"unknown",status:a.status||"error",errorType:a.errorType||"",errorCode:a.errorCode||"",errorSource:a.errorSource||"",provider:a.provider||"unknown",model:a.model||"unknown",endpoint:a.endpoint||"unknown",apiKey:a.apiKey||"",sampleMessage:a.sampleMessage||"",serverImpacting:["gateway","upstream"].includes(a.faultOwner||"")})),w=await A(c,u(k.clause),p),x=y(k.clause,r,["gateway","upstream"]),C=y(k.clause,r,["client"]),D=y(k.clause,r,["rate_limit"]),[E,F,G,H]=await Promise.all([A(c,u(x),p),A(c,u(C),p),A(c,u(D),p),A(c,`SELECT ${r} AS key, ${r} AS label, COUNT(*) AS requests, MAX(created_at) AS lastSeen
         FROM request_error_events
         ${k.clause}
         GROUP BY ${r}
         ORDER BY requests DESC, lastSeen DESC
         LIMIT ${o}`,p)]),I=new Map(H.map(a=>[j(a.key)||"unknown",l(a.requests,0)])),J=I.get("gateway")||0,K=I.get("upstream")||0,L=I.get("client")||0,M=I.get("rate_limit")||0,N=I.get("unknown")||0,O=J+K,P=async(a,b=a)=>(await A(c,`SELECT COALESCE(NULLIF(${a}, ''), 'unknown') AS key, COALESCE(NULLIF(${a}, ''), 'unknown') AS label, COUNT(*) AS requests, MAX(created_at) AS lastSeen
         FROM request_error_events
         ${k.clause}
         GROUP BY COALESCE(NULLIF(${a}, ''), 'unknown')
         ORDER BY requests DESC, lastSeen DESC
         LIMIT ${o}`,p)).map(a=>z(a,{[b]:a.key})),Q="postgres"===c.type?`$${k.params.length+1}`:"?",R=await A(c,`SELECT id, created_at AS createdAt, request_id AS requestId, provider, model, connection_id AS connectionId, endpoint,
              gateway_status_code AS gatewayStatusCode, upstream_status_code AS upstreamStatusCode, status_class AS statusClass,
              ${r} AS faultOwner,
              error_source AS errorSource, error_type AS errorType, error_code AS errorCode,
              error_message_short AS errorMessageShort, api_key_fingerprint AS apiKeyFingerprint,
              client_ip_normalized AS clientIp, source_tool AS sourceTool, session_id AS sessionId, latency_ms AS latencyMs
       FROM request_error_events
       ${k.clause}
       ORDER BY created_at DESC
       LIMIT ${Q}`,[...k.params,50]);return{disabled:!1,total:n,summary:{total:n,serverImpacting:O,gateway:J,upstream:K,client:L,rateLimit:M,unknown:N,serverImpactingRate:n?O/n:0,clientRate:n?L/n:0,rateLimitRate:n?M/n:0},topErrors:v(w),topServerErrors:v(E),topClientErrors:v(F),topRateLimitErrors:v(G),byFaultOwner:H.map(a=>z(a,{faultOwner:a.key})),byStatusCode:await P(q,"status"),byStatusClass:await P("status_class","statusClass"),byErrorType:await P("error_type","errorType"),byErrorSource:await P("error_source","errorSource"),byProvider:await P("provider","provider"),byModel:await P("model","model"),byClientIp:await P("client_ip_normalized","clientIp"),bySourceTool:await P("source_tool","sourceTool"),recent:R}}catch(a){return w({disabled:!0,error:a?.message||String(a)})}finally{await c.close()}}},45903:(a,b,c)=>{c.d(b,{AP:()=>m,BY:()=>w,I6:()=>k,L7:()=>l,dX:()=>v,r:()=>j});var d=c(89718),e=c(33873),f=c.n(e),g=c(29021),h=c.n(g);let i={enabled:!1,type:"sqlite",sqlitePath:"",host:"",port:"",database:"",username:"",password:"",ssl:!1,createDatabase:!1,logClientRequest:!0,logSourceRequest:!0,logTargetRequest:!0,logProviderResponse:!1,logErrors:!0,retentionDays:30};function j(a){let b={...a||{}};return b.password&&(b.password="********"),b}function k(a={},b={}){let c={...i,...b||{},...a||{}};c.enabled=!!c.enabled,c.type=["sqlite","postgres","mysql"].includes(c.type)?c.type:"sqlite",c.ssl=!!c.ssl,c.createDatabase=!!c.createDatabase,c.logClientRequest=!1!==c.logClientRequest,c.logSourceRequest=!1!==c.logSourceRequest,c.logTargetRequest=!1!==c.logTargetRequest,c.logProviderResponse=!0===c.logProviderResponse,c.logErrors=!1!==c.logErrors;let d=Number(c.retentionDays);return c.retentionDays=Number.isFinite(d)&&d>0?Math.floor(d):30,"********"===c.password&&(c.password=b?.password||""),c.host=String(c.host||"").trim(),c.port=String(c.port||"").trim(),c.database=String(c.database||"").trim(),c.username=String(c.username||"").trim(),c.password=String(c.password||""),c.sqlitePath=String(c.sqlitePath||"").trim(),c}async function l(){let a=await (0,d.mt)();return{...i,...a?.promptLogDb||{}}}async function m(a){let b=await (0,d.mt)(),c=k(a,b?.promptLogDb||{});return await (0,d.Xx)({promptLogDb:c}),c}async function n(a){let b,d=a.sqlitePath||(b=process.env.DATA_DIR||"/var/lib/bluerouter",f().join(b,"logs","promptLogs.sqlite"));h().mkdirSync(f().dirname(d),{recursive:!0});try{let a=await Promise.resolve().then(c.t.bind(c,87550,23)),b=new(a.default||a)(d);return b.pragma("journal_mode = WAL"),b.pragma("busy_timeout = 5000"),{type:"sqlite",sqlitePath:d,exec(a){b.exec(a)},all:(a,c=[])=>b.prepare(a).all(...c),close(){b.close()}}}catch{let a=new(await Promise.resolve().then(c.t.bind(c,80099,23))).DatabaseSync(d);return a.exec("PRAGMA journal_mode = WAL"),a.exec("PRAGMA busy_timeout = 5000"),{type:"sqlite",sqlitePath:d,exec(b){a.exec(b)},all:(b,c=[])=>a.prepare(b).all(...c),close(){a.close()}}}}async function o(a,b=null){let d=new(await Promise.resolve().then(c.bind(c,64939))).Client({host:a.host,port:Number(a.port||5432),database:b||a.database,user:a.username,password:a.password,ssl:!!a.ssl&&{rejectUnauthorized:!1}});return await d.connect(),{type:"postgres",client:d,async exec(a){await d.query(a)},async close(){await d.end()}}}async function p(a,b=!0){let d=await c.e(8491).then(c.t.bind(c,38491,19)),e=await d.createConnection({host:a.host,port:Number(a.port||3306),database:b?a.database:void 0,user:a.username,password:a.password,ssl:a.ssl?{}:void 0,multipleStatements:!0});return{type:"mysql",conn:e,async exec(a){await e.query(a)},async close(){await e.end()}}}async function q(a){let b=new Set(a.all("PRAGMA table_info(prompt_logs)").map(a=>a.name)),c=(c,d)=>{b.has(c)||a.exec(`ALTER TABLE prompt_logs ADD COLUMN ${c} ${d};`)};c("client_ip","TEXT"),c("client_port","TEXT"),c("client_user_agent","TEXT"),c("client_host","TEXT"),c("source_tool","TEXT"),c("source_tool_label","TEXT"),c("source_host","TEXT"),c("provider","TEXT"),c("account_name","TEXT"),c("connection_id","TEXT"),c("display_model","TEXT"),a.exec("CREATE INDEX IF NOT EXISTS idx_prompt_logs_client_ip ON prompt_logs(client_ip);"),a.exec("CREATE INDEX IF NOT EXISTS idx_prompt_logs_source_tool ON prompt_logs(source_tool);")}async function r(a){await a.exec(`
    ALTER TABLE prompt_logs ADD COLUMN IF NOT EXISTS client_ip TEXT;
    ALTER TABLE prompt_logs ADD COLUMN IF NOT EXISTS client_port TEXT;
    ALTER TABLE prompt_logs ADD COLUMN IF NOT EXISTS client_user_agent TEXT;
    ALTER TABLE prompt_logs ADD COLUMN IF NOT EXISTS client_host TEXT;
    ALTER TABLE prompt_logs ADD COLUMN IF NOT EXISTS source_tool TEXT;
    ALTER TABLE prompt_logs ADD COLUMN IF NOT EXISTS source_tool_label TEXT;
    ALTER TABLE prompt_logs ADD COLUMN IF NOT EXISTS source_host TEXT;
    ALTER TABLE prompt_logs ADD COLUMN IF NOT EXISTS provider TEXT;
    ALTER TABLE prompt_logs ADD COLUMN IF NOT EXISTS account_name TEXT;
    ALTER TABLE prompt_logs ADD COLUMN IF NOT EXISTS connection_id TEXT;
    ALTER TABLE prompt_logs ADD COLUMN IF NOT EXISTS display_model TEXT;

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_client_ip
      ON prompt_logs(client_ip);

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_source_tool
      ON prompt_logs(source_tool);
  `)}async function s(a,b,c,d){let[e]=await a.query(`
    SELECT 1 AS found
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = ?
      AND TABLE_NAME = ?
      AND COLUMN_NAME = ?
    LIMIT 1
    `,[b,c,d]);return e.length>0}async function t(a,b,c,d){let[e]=await a.query(`
    SELECT 1 AS found
    FROM INFORMATION_SCHEMA.STATISTICS
    WHERE TABLE_SCHEMA = ?
      AND TABLE_NAME = ?
      AND INDEX_NAME = ?
    LIMIT 1
    `,[b,c,d]);return e.length>0}async function u(a,b){let c=async(c,d)=>{await s(a.conn,b.database,"prompt_logs",c)||await a.conn.query(`ALTER TABLE prompt_logs ADD COLUMN ${c} ${d}`)};await c("client_ip","VARCHAR(64)"),await c("client_port","VARCHAR(32)"),await c("client_user_agent","TEXT"),await c("client_host","TEXT"),await c("source_tool","VARCHAR(80)"),await c("source_tool_label","VARCHAR(120)"),await c("source_host","VARCHAR(255)"),await c("provider","VARCHAR(120)"),await c("account_name","VARCHAR(255)"),await c("connection_id","VARCHAR(120)"),await c("display_model","VARCHAR(512)"),await t(a.conn,b.database,"prompt_logs","idx_prompt_logs_client_ip")||await a.conn.query("CREATE INDEX idx_prompt_logs_client_ip ON prompt_logs(client_ip)"),await t(a.conn,b.database,"prompt_logs","idx_prompt_logs_source_tool")||await a.conn.query("CREATE INDEX idx_prompt_logs_source_tool ON prompt_logs(source_tool)")}async function v(a=null){let b=k(a||await l());if("sqlite"===b.type){let a=await n(b);try{return a.exec(`
    CREATE TABLE IF NOT EXISTS prompt_logs (
      id TEXT PRIMARY KEY,
      created_at TEXT NOT NULL,
      session_id TEXT,
      source_format TEXT,
      target_format TEXT,
      model TEXT,
      endpoint TEXT,
      stage TEXT,
      provider_url TEXT,
      provider TEXT,
      account_name TEXT,
      connection_id TEXT,
      display_model TEXT,
      client_ip TEXT,
      client_port TEXT,
      client_user_agent TEXT,
      client_host TEXT,
      source_tool TEXT,
      source_tool_label TEXT,
      source_host TEXT,
      prompt_text TEXT,
      full_request_json TEXT,
      response_text TEXT,
      status_code INTEGER,
      error_text TEXT,
      meta_json TEXT
    );

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_created_at
      ON prompt_logs(created_at DESC);

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_model
      ON prompt_logs(model);

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_stage
      ON prompt_logs(stage);

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_session
      ON prompt_logs(session_id);

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_client_ip
      ON prompt_logs(client_ip);

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_source_tool
      ON prompt_logs(source_tool);
  `),await q(a),{ok:!0,type:"sqlite",message:"SQLite prompt log schema is ready",sqlitePath:a.sqlitePath}}finally{a.close()}}if("postgres"===b.type){if(!b.host||!b.database||!b.username)throw Error("PostgreSQL host, database, and username are required");if(b.createDatabase){let a=await o(b,"postgres");try{let c=await a.client.query("SELECT 1 FROM pg_database WHERE datname = $1",[b.database]);if(0===c.rowCount){let c=b.database.replace(/"/g,'""');await a.client.query(`CREATE DATABASE "${c}"`)}}finally{await a.close()}}let a=await o(b);try{return await a.exec(`
    CREATE TABLE IF NOT EXISTS prompt_logs (
      id TEXT PRIMARY KEY,
      created_at TIMESTAMPTZ NOT NULL,
      session_id TEXT,
      source_format TEXT,
      target_format TEXT,
      model TEXT,
      endpoint TEXT,
      stage TEXT,
      provider_url TEXT,
      provider TEXT,
      account_name TEXT,
      connection_id TEXT,
      display_model TEXT,
      client_ip TEXT,
      client_port TEXT,
      client_user_agent TEXT,
      client_host TEXT,
      source_tool TEXT,
      source_tool_label TEXT,
      source_host TEXT,
      prompt_text TEXT,
      full_request_json JSONB,
      response_text TEXT,
      status_code INTEGER,
      error_text TEXT,
      meta_json JSONB
    );

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_created_at
      ON prompt_logs(created_at DESC);

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_model
      ON prompt_logs(model);

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_stage
      ON prompt_logs(stage);

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_session
      ON prompt_logs(session_id);

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_client_ip
      ON prompt_logs(client_ip);

    CREATE INDEX IF NOT EXISTS idx_prompt_logs_source_tool
      ON prompt_logs(source_tool);
  `),await r(a),{ok:!0,type:"postgres",message:"PostgreSQL prompt log schema is ready"}}finally{await a.close()}}if("mysql"===b.type){if(!b.host||!b.database||!b.username)throw Error("MySQL host, database, and username are required");if(b.createDatabase){let a=await p(b,!1);try{let c=b.database.replace(/`/g,"``");await a.exec(`CREATE DATABASE IF NOT EXISTS \`${c}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`)}finally{await a.close()}}let a=await p(b,!0);try{return await a.exec(`
    CREATE TABLE IF NOT EXISTS prompt_logs (
      id VARCHAR(80) PRIMARY KEY,
      created_at DATETIME(3) NOT NULL,
      session_id VARCHAR(255),
      source_format VARCHAR(80),
      target_format VARCHAR(80),
      model VARCHAR(255),
      endpoint TEXT,
      stage VARCHAR(80),
      provider_url TEXT,
      provider VARCHAR(120),
      account_name VARCHAR(255),
      connection_id VARCHAR(120),
      display_model VARCHAR(512),
      client_ip VARCHAR(64),
      client_port VARCHAR(32),
      client_user_agent TEXT,
      client_host TEXT,
      source_tool VARCHAR(80),
      source_tool_label VARCHAR(120),
      source_host VARCHAR(255),
      prompt_text LONGTEXT,
      full_request_json JSON,
      response_text LONGTEXT,
      status_code INT,
      error_text TEXT,
      meta_json JSON,
      INDEX idx_prompt_logs_created_at (created_at),
      INDEX idx_prompt_logs_model (model),
      INDEX idx_prompt_logs_stage (stage),
      INDEX idx_prompt_logs_session (session_id),
      INDEX idx_prompt_logs_client_ip (client_ip),
      INDEX idx_prompt_logs_source_tool (source_tool)
    );
  `),await u(a,b),{ok:!0,type:"mysql",message:"MySQL prompt log schema is ready"}}finally{await a.close()}}throw Error(`Unsupported database type: ${b.type}`)}async function w(a=null){let b=k(a||await l());if("sqlite"===b.type){let a=await n(b);try{return a.exec("SELECT 1;"),{ok:!0,type:"sqlite",message:"SQLite connection OK",sqlitePath:a.sqlitePath}}finally{a.close()}}if("postgres"===b.type){let a=await o(b);try{return await a.exec("SELECT 1;"),{ok:!0,type:"postgres",message:"PostgreSQL connection OK"}}finally{await a.close()}}if("mysql"===b.type){let a=await p(b,!0);try{return await a.exec("SELECT 1;"),{ok:!0,type:"mysql",message:"MySQL connection OK"}}finally{await a.close()}}throw Error(`Unsupported database type: ${b.type}`)}}};