"use strict";exports.id=3941,exports.ids=[3941],exports.modules={43941:(a,b,c)=>{c.d(b,{runMigrationOnce:()=>B});var d=c(73024),e=c.n(d),f=c(76760),g=c.n(f),h=c(95658),i=c(63775);let j=["CREATE INDEX IF NOT EXISTS idx_uh_ts_status ON usageHistory(timestamp DESC, status)","CREATE INDEX IF NOT EXISTS idx_uh_ts_provider ON usageHistory(timestamp DESC, provider)","CREATE INDEX IF NOT EXISTS idx_uh_ts_model ON usageHistory(timestamp DESC, model)","CREATE INDEX IF NOT EXISTS idx_uh_ts_conn ON usageHistory(timestamp DESC, connectionId)","CREATE INDEX IF NOT EXISTS idx_uh_ts_endpoint ON usageHistory(timestamp DESC, endpoint)","CREATE INDEX IF NOT EXISTS idx_uh_ts_apikey ON usageHistory(timestamp DESC, apiKey)","CREATE INDEX IF NOT EXISTS idx_uh_provider_model_ts ON usageHistory(provider, model, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_status_ts ON usageHistory(status, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_endpoint_ts ON usageHistory(endpoint, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_apikey_ts ON usageHistory(apiKey, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_conn_ts ON usageHistory(connectionId, timestamp DESC)"],k={apiKeyId:"TEXT",apiKeyFingerprint:"TEXT",apiKeyName:"TEXT",apiKeyOwner:"TEXT",requestId:"TEXT",sessionId:"TEXT",clientIp:"TEXT",clientIpNormalized:"TEXT",clientHost:"TEXT",clientUserAgent:"TEXT",sourceTool:"TEXT",sourceToolLabel:"TEXT",sourceHost:"TEXT",latencyMs:"INTEGER DEFAULT 0",ttftMs:"INTEGER DEFAULT 0",statusCode:"INTEGER",errorCode:"TEXT",errorType:"TEXT",errorMessageShort:"TEXT",isStreaming:"INTEGER DEFAULT 0",isCombo:"INTEGER DEFAULT 0",comboName:"TEXT",totalTokens:"INTEGER DEFAULT 0",cachedTokens:"INTEGER DEFAULT 0",reasoningTokens:"INTEGER DEFAULT 0"},l=["CREATE INDEX IF NOT EXISTS idx_uh_request_id ON usageHistory(requestId)","CREATE INDEX IF NOT EXISTS idx_uh_apikey_id_ts ON usageHistory(apiKeyId, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_apikey_fp_ts ON usageHistory(apiKeyFingerprint, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_ip_ts ON usageHistory(clientIpNormalized, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_tool_ts ON usageHistory(sourceTool, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_session_ts ON usageHistory(sessionId, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_status_code_ts ON usageHistory(statusCode, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_error_type_ts ON usageHistory(errorType, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_latency_ts ON usageHistory(timestamp DESC, latencyMs)","CREATE INDEX IF NOT EXISTS idx_uh_combo_ts ON usageHistory(isCombo, comboName, timestamp DESC)"],m=[`CREATE TABLE IF NOT EXISTS usageHourlyRollup(
    bucket TEXT NOT NULL,
    dimension TEXT NOT NULL,
    key TEXT NOT NULL,
    requests INTEGER DEFAULT 0,
    success INTEGER DEFAULT 0,
    errors INTEGER DEFAULT 0,
    promptTokens INTEGER DEFAULT 0,
    completionTokens INTEGER DEFAULT 0,
    totalTokens INTEGER DEFAULT 0,
    cachedTokens INTEGER DEFAULT 0,
    reasoningTokens INTEGER DEFAULT 0,
    cost REAL DEFAULT 0,
    lastSeen TEXT,
    PRIMARY KEY (bucket, dimension, key)
  )`,`CREATE TABLE IF NOT EXISTS usageDailyRollup(
    bucket TEXT NOT NULL,
    dimension TEXT NOT NULL,
    key TEXT NOT NULL,
    requests INTEGER DEFAULT 0,
    success INTEGER DEFAULT 0,
    errors INTEGER DEFAULT 0,
    promptTokens INTEGER DEFAULT 0,
    completionTokens INTEGER DEFAULT 0,
    totalTokens INTEGER DEFAULT 0,
    cachedTokens INTEGER DEFAULT 0,
    reasoningTokens INTEGER DEFAULT 0,
    cost REAL DEFAULT 0,
    lastSeen TEXT,
    PRIMARY KEY (bucket, dimension, key)
  )`,"CREATE INDEX IF NOT EXISTS idx_uhr_dim_bucket ON usageHourlyRollup(dimension, bucket DESC)","CREATE INDEX IF NOT EXISTS idx_uhr_bucket ON usageHourlyRollup(bucket DESC)","CREATE INDEX IF NOT EXISTS idx_udr_dim_bucket ON usageDailyRollup(dimension, bucket DESC)","CREATE INDEX IF NOT EXISTS idx_udr_bucket ON usageDailyRollup(bucket DESC)"];function n(a,b,c){let d=function(a,b){try{return new Set((a.all(`PRAGMA table_info(${b})`)||[]).map(a=>a.name))}catch{return new Set}}(a,b);for(let[e,f]of Object.entries(c))d.has(e)||a.exec(`ALTER TABLE ${b} ADD COLUMN ${e} ${f}`)}let o=[{version:1,name:"initial",up(a){for(let[b,c]of Object.entries(i.CG))for(let d of(a.exec((0,i.zE)(b,c)),c.indexes||[]))a.exec(d)}},{version:2,name:"usage-history-analytics-indexes",up(a){for(let b of j)a.exec(b)}},{version:3,name:"request-observability-rollups",up(a){for(let b of(n(a,"apiKeys",{ownerUser:"TEXT DEFAULT ''",createdByUser:"TEXT DEFAULT ''",allowedModels:"TEXT DEFAULT '[]'"}),n(a,"usageHistory",k),l))a.exec(b);for(let b of m)a.exec(b);a.exec("CREATE INDEX IF NOT EXISTS idx_ak_owner ON apiKeys(ownerUser)"),a.exec("CREATE INDEX IF NOT EXISTS idx_ak_created_by ON apiKeys(createdByUser)"),a.exec(`UPDATE usageHistory
              SET totalTokens = COALESCE(promptTokens, 0) + COALESCE(completionTokens, 0)
              WHERE totalTokens IS NULL OR totalTokens = 0`),a.exec(`UPDATE usageHistory
              SET apiKeyId = COALESCE(NULLIF(apiKeyId, ''), (SELECT id FROM apiKeys WHERE apiKeys.key = usageHistory.apiKey LIMIT 1)),
                  apiKeyName = COALESCE(NULLIF(apiKeyName, ''), (SELECT name FROM apiKeys WHERE apiKeys.key = usageHistory.apiKey LIMIT 1)),
                  apiKeyOwner = COALESCE(NULLIF(apiKeyOwner, ''), (SELECT ownerUser FROM apiKeys WHERE apiKeys.key = usageHistory.apiKey LIMIT 1))
              WHERE apiKey IS NOT NULL AND apiKey <> ''`),a.exec(`UPDATE usageHistory
              SET apiKeyFingerprint = CASE
                WHEN apiKey IS NULL OR apiKey = '' THEN 'local-no-key'
                WHEN length(apiKey) <= 12 THEN apiKey
                ELSE substr(apiKey, 1, 8) || '...' || substr(apiKey, -4)
              END
              WHERE apiKeyFingerprint IS NULL OR apiKeyFingerprint = ''`),a.exec(`UPDATE usageHistory
              SET apiKey = apiKeyFingerprint
              WHERE apiKey IS NOT NULL AND apiKey <> '' AND apiKeyFingerprint IS NOT NULL AND apiKeyFingerprint <> ''`)}},{version:4,name:"api-key-admin-disabled",up(a){(function(a,b){try{return new Set((a.all(`PRAGMA table_info(${b})`)||[]).map(a=>a.name))}catch{return new Set}})(a,"apiKeys").has("adminDisabled")||a.exec("ALTER TABLE apiKeys ADD COLUMN adminDisabled INTEGER DEFAULT 0"),a.exec("CREATE INDEX IF NOT EXISTS idx_ak_admin_disabled ON apiKeys(adminDisabled)")}}].sort((a,b)=>a.version-b.version);var p=c(62674);let q=null;function r(){if(q)return q;try{let a=g().join(process.cwd(),"package.json");q=JSON.parse(e().readFileSync(a,"utf-8")).version||"0.0.0"}catch{q="0.0.0"}return q}function s(a){(0,h.Jh)();let b=r(),c=`${a}-${b}-${function(a=new Date){let b=a=>String(a).padStart(2,"0");return`${a.getFullYear()}${b(a.getMonth()+1)}${b(a.getDate())}-${b(a.getHours())}${b(a.getMinutes())}${b(a.getSeconds())}`}()}`,d=g().join(h.KQ,c);return e().mkdirSync(d,{recursive:!0}),d}function t(a,b,c=null){if(!e().existsSync(a))return null;let d=c||g().basename(a),f=g().join(b,d);return e().copyFileSync(a,f),f}function u(){if(e().existsSync(h.KQ))for(let a of e().readdirSync(h.KQ,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>({name:a.name,full:g().join(h.KQ,a.name),mtime:e().statSync(g().join(h.KQ,a.name)).mtimeMs})).sort((a,b)=>b.mtime-a.mtime).slice(5))try{e().rmSync(a.full,{recursive:!0,force:!0})}catch{}}var v=c(644);let w=g().join(h.HG,".migrated-from-json"),x=new WeakSet;class y extends Error{constructor(a,b){super(a),this.name="MigrationAborted",this.droppedRows=b}}function z(a,b,c,d,e){let f=[];for(let a of c)try{d(a)}catch(b){f.push({...e(a),reason:b.message})}let g=a.get(`SELECT COUNT(*) as c FROM ${b}`)?.c??0;if(g!==c.length)throw console.warn(`[DB][migrate] ${b} row-count mismatch: expected ${c.length}, got ${g}. Dropped:`,f),new y(`${b} row-count mismatch: expected ${c.length}, got ${g}`,f)}function A(a){if(!e().existsSync(a))return null;try{return JSON.parse(e().readFileSync(a,"utf-8"))}catch{return null}}async function B(a){if(x.has(a))return;x.add(a);let b=function(a){try{let b=a.get("SELECT COUNT(*) as c FROM _meta");return!b||0===b.c}catch{return!0}}(a),c=function(a){a.exec((0,i.zE)("_meta",i.CG._meta));let b=parseInt((0,p.dy)(a,"schemaVersion","0"),10)||0;if(b>=(o.length?o[o.length-1].version:0))return{applied:0,from:b,to:b};let c=o.filter(a=>a.version>b),d=b;for(let b of c)a.transaction(()=>{b.up(a),(0,p.np)(a,"schemaVersion",b.version)}),d=b.version,console.log(`[DB][migrate] applied #${b.version} ${b.name}`);return{applied:c.length,from:b,to:d}}(a);for(let[b,c]of Object.entries(i.CG)){a.exec((0,i.zE)(b,c));let d=new Set(a.all(`PRAGMA table_info(${b})`).map(a=>a.name));for(let[e,f]of Object.entries(c.columns))if(!d.has(e)){let c=f.replace(/PRIMARY KEY( AUTOINCREMENT)?/i,"").replace(/UNIQUE/i,"").trim();try{a.exec(`ALTER TABLE ${b} ADD COLUMN ${e} ${c}`),console.log(`[DB][sync] +column ${b}.${e}`)}catch(a){console.warn(`[DB][sync] add column ${b}.${e} failed: ${a.message}`)}}for(let b of c.indexes||[])try{a.exec(b)}catch{}}let d=e().existsSync(w),f=A(h.Or.main),g=A(h.Or.usage),j=A(h.Or.disabled),k=A(h.Or.details);if(b&&(f||g||j||k)&&!d){let b=Date.now(),c=s("migrate-from-json");for(let a of Object.values(h.Or))t(a,c);try{a.transaction(()=>{if(f&&"object"==typeof f){for(let[b,c]of(f.settings&&a.run("INSERT INTO settings(id, data) VALUES(1, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data",[(0,v.s)(f.settings)]),z(a,"providerConnections",f.providerConnections||[],b=>{let{id:c,provider:d,authType:e,name:f,email:g,priority:h,isActive:i,createdAt:j,updatedAt:k,...l}=b;a.run("INSERT OR REPLACE INTO providerConnections(id, provider, authType, name, email, priority, isActive, data, createdAt, updatedAt) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[c,d,e||"oauth",f||null,g||null,h||null,+(!1!==i),(0,v.s)(l),j||new Date().toISOString(),k||new Date().toISOString()])},a=>({id:a.id??null,provider:a.provider??null,name:a.name??null})),z(a,"providerNodes",f.providerNodes||[],b=>{let{id:c,type:d,name:e,createdAt:f,updatedAt:g,...h}=b;a.run("INSERT OR REPLACE INTO providerNodes(id, type, name, data, createdAt, updatedAt) VALUES(?, ?, ?, ?, ?, ?)",[c,d||null,e||null,(0,v.s)(h),f||new Date().toISOString(),g||new Date().toISOString()])},a=>({id:a.id??null,type:a.type??null,name:a.name??null})),z(a,"proxyPools",f.proxyPools||[],b=>{let{id:c,isActive:d,testStatus:e,createdAt:f,updatedAt:g,...h}=b;a.run("INSERT OR REPLACE INTO proxyPools(id, isActive, testStatus, data, createdAt, updatedAt) VALUES(?, ?, ?, ?, ?, ?)",[c,+(!1!==d),e||"unknown",(0,v.s)(h),f||new Date().toISOString(),g||new Date().toISOString()])},a=>({id:a.id??null})),z(a,"apiKeys",f.apiKeys||[],b=>{a.run("INSERT OR REPLACE INTO apiKeys(id, key, name, machineId, isActive, createdAt) VALUES(?, ?, ?, ?, ?, ?)",[b.id,b.key,b.name||null,b.machineId||null,+(!1!==b.isActive),b.createdAt||new Date().toISOString()])},a=>({id:a.id??null,name:a.name??null})),z(a,"combos",f.combos||[],b=>{a.run("INSERT OR REPLACE INTO combos(id, name, kind, models, createdAt, updatedAt) VALUES(?, ?, ?, ?, ?, ?)",[b.id,b.name,b.kind||null,(0,v.s)(b.models||[]),b.createdAt||new Date().toISOString(),b.updatedAt||new Date().toISOString()])},a=>({id:a.id??null,name:a.name??null})),Object.entries(f.modelAliases||{})))a.run("INSERT OR REPLACE INTO kv(scope, key, value) VALUES('modelAliases', ?, ?)",[b,(0,v.s)(c)]);for(let b of f.customModels||[]){let c=`${b.providerAlias}|${b.id}|${b.type||"llm"}`;a.run("INSERT OR REPLACE INTO kv(scope, key, value) VALUES('customModels', ?, ?)",[c,(0,v.s)(b)])}for(let[b,c]of Object.entries(f.mitmAlias||{}))a.run("INSERT OR REPLACE INTO kv(scope, key, value) VALUES('mitmAlias', ?, ?)",[b,(0,v.s)(c||{})]);for(let[b,c]of Object.entries(f.pricing||{}))a.run("INSERT OR REPLACE INTO kv(scope, key, value) VALUES('pricing', ?, ?)",[b,(0,v.s)(c||{})])}if(g&&"object"==typeof g){for(let b of g.history||[]){let c=b.tokens||{};a.run("INSERT INTO usageHistory(timestamp, provider, model, connectionId, apiKey, endpoint, promptTokens, completionTokens, cost, status, tokens, meta) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[b.timestamp||new Date().toISOString(),b.provider||null,b.model||null,b.connectionId||null,b.apiKey||null,b.endpoint||null,c.prompt_tokens||c.input_tokens||0,c.completion_tokens||c.output_tokens||0,b.cost||0,b.status||"ok",(0,v.s)(c),(0,v.s)({})])}for(let[b,c]of Object.entries(g.dailySummary||{}))a.run("INSERT OR REPLACE INTO usageDaily(dateKey, data) VALUES(?, ?)",[b,(0,v.s)(c)]);"number"==typeof g.totalRequestsLifetime&&(0,p.np)(a,"totalRequestsLifetime",g.totalRequestsLifetime)}if(j&&"object"==typeof j.disabled)for(let[b,c]of Object.entries(j.disabled))a.run("INSERT OR REPLACE INTO kv(scope, key, value) VALUES('disabledModels', ?, ?)",[b,(0,v.s)(c||[])]);if(k&&Array.isArray(k.records))for(let b of k.records)a.run("INSERT OR REPLACE INTO requestDetails(id, timestamp, provider, model, connectionId, status, data) VALUES(?, ?, ?, ?, ?, ?, ?)",[b.id,b.timestamp||new Date().toISOString(),b.provider||null,b.model||null,b.connectionId||null,b.status||null,(0,v.s)(b)]);(0,p.np)(a,"appVersion",r()),(0,p.np)(a,"migratedAt",new Date().toISOString())})}catch(a){if(a instanceof y)return void console.error(`[DB][migrate] aborted: ${a.message} | legacy JSON kept | backup: ${c}`);throw a}try{e().writeFileSync(w,new Date().toISOString())}catch{}u(),console.log(`[DB][migrate] JSON → SQLite in ${Date.now()-b}ms | legacy JSON kept at DATA_DIR | backup: ${c}`);return}if(b)return void(0,p.np)(a,"appVersion",r());let l=(0,p.dy)(a,"appVersion",null),m=r();if(l&&l!==m){let b=s(`upgrade-${l}-to-${m}`);try{t(h.AL,b)}catch{}(0,p.np)(a,"appVersion",m),u(),console.log(`[DB][migrate] App ${l} → ${m} | schema ${c.from} → ${c.to} | backup: ${b}`)}else if(c.applied>0){let a=s(`schema-${c.from}-to-${c.to}`);try{t(h.AL,a)}catch{}u()}}},63775:(a,b,c)=>{c.d(b,{CG:()=>e,oG:()=>d,zE:()=>f});let d=`
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA temp_store = MEMORY;
PRAGMA mmap_size = 30000000;
PRAGMA cache_size = -64000;
PRAGMA foreign_keys = ON;
PRAGMA busy_timeout = 5000;
`,e={_meta:{columns:{key:"TEXT PRIMARY KEY",value:"TEXT NOT NULL"}},settings:{columns:{id:"INTEGER PRIMARY KEY CHECK (id = 1)",data:"TEXT NOT NULL"}},providerConnections:{columns:{id:"TEXT PRIMARY KEY",provider:"TEXT NOT NULL",authType:"TEXT NOT NULL",name:"TEXT",email:"TEXT",priority:"INTEGER",isActive:"INTEGER DEFAULT 1",data:"TEXT NOT NULL",createdAt:"TEXT NOT NULL",updatedAt:"TEXT NOT NULL"},indexes:["CREATE INDEX IF NOT EXISTS idx_pc_provider ON providerConnections(provider)","CREATE INDEX IF NOT EXISTS idx_pc_provider_active ON providerConnections(provider, isActive)","CREATE INDEX IF NOT EXISTS idx_pc_priority ON providerConnections(provider, priority)"]},providerNodes:{columns:{id:"TEXT PRIMARY KEY",type:"TEXT",name:"TEXT",data:"TEXT NOT NULL",createdAt:"TEXT NOT NULL",updatedAt:"TEXT NOT NULL"},indexes:["CREATE INDEX IF NOT EXISTS idx_pn_type ON providerNodes(type)"]},proxyPools:{columns:{id:"TEXT PRIMARY KEY",isActive:"INTEGER DEFAULT 1",testStatus:"TEXT",data:"TEXT NOT NULL",createdAt:"TEXT NOT NULL",updatedAt:"TEXT NOT NULL"},indexes:["CREATE INDEX IF NOT EXISTS idx_pp_active ON proxyPools(isActive)","CREATE INDEX IF NOT EXISTS idx_pp_status ON proxyPools(testStatus)"]},apiKeys:{columns:{id:"TEXT PRIMARY KEY",key:"TEXT UNIQUE NOT NULL",name:"TEXT",machineId:"TEXT",isActive:"INTEGER DEFAULT 1",adminDisabled:"INTEGER DEFAULT 0",allowedModels:"TEXT DEFAULT '[]'",ownerUser:"TEXT DEFAULT ''",createdByUser:"TEXT DEFAULT ''",createdAt:"TEXT NOT NULL"},indexes:["CREATE INDEX IF NOT EXISTS idx_ak_key ON apiKeys(key)","CREATE INDEX IF NOT EXISTS idx_ak_owner ON apiKeys(ownerUser)","CREATE INDEX IF NOT EXISTS idx_ak_created_by ON apiKeys(createdByUser)","CREATE INDEX IF NOT EXISTS idx_ak_admin_disabled ON apiKeys(adminDisabled)"]},combos:{columns:{id:"TEXT PRIMARY KEY",name:"TEXT UNIQUE NOT NULL",kind:"TEXT",models:"TEXT NOT NULL",createdAt:"TEXT NOT NULL",updatedAt:"TEXT NOT NULL"},indexes:["CREATE INDEX IF NOT EXISTS idx_combo_name ON combos(name)"]},kv:{columns:{scope:"TEXT NOT NULL",key:"TEXT NOT NULL",value:"TEXT NOT NULL"},primaryKey:"PRIMARY KEY (scope, key)",indexes:["CREATE INDEX IF NOT EXISTS idx_kv_scope ON kv(scope)"]},usageHistory:{columns:{id:"INTEGER PRIMARY KEY AUTOINCREMENT",timestamp:"TEXT NOT NULL",provider:"TEXT",model:"TEXT",connectionId:"TEXT",apiKey:"TEXT",apiKeyId:"TEXT",apiKeyFingerprint:"TEXT",apiKeyName:"TEXT",apiKeyOwner:"TEXT",endpoint:"TEXT",requestId:"TEXT",sessionId:"TEXT",clientIp:"TEXT",clientIpNormalized:"TEXT",clientHost:"TEXT",clientUserAgent:"TEXT",sourceTool:"TEXT",sourceToolLabel:"TEXT",sourceHost:"TEXT",latencyMs:"INTEGER DEFAULT 0",ttftMs:"INTEGER DEFAULT 0",statusCode:"INTEGER",errorCode:"TEXT",errorType:"TEXT",errorMessageShort:"TEXT",isStreaming:"INTEGER DEFAULT 0",isCombo:"INTEGER DEFAULT 0",comboName:"TEXT",promptTokens:"INTEGER DEFAULT 0",completionTokens:"INTEGER DEFAULT 0",totalTokens:"INTEGER DEFAULT 0",cachedTokens:"INTEGER DEFAULT 0",reasoningTokens:"INTEGER DEFAULT 0",cost:"REAL DEFAULT 0",status:"TEXT",tokens:"TEXT",meta:"TEXT"},indexes:["CREATE INDEX IF NOT EXISTS idx_uh_ts ON usageHistory(timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_provider ON usageHistory(provider)","CREATE INDEX IF NOT EXISTS idx_uh_model ON usageHistory(model)","CREATE INDEX IF NOT EXISTS idx_uh_conn ON usageHistory(connectionId)","CREATE INDEX IF NOT EXISTS idx_uh_ts_status ON usageHistory(timestamp DESC, status)","CREATE INDEX IF NOT EXISTS idx_uh_ts_provider ON usageHistory(timestamp DESC, provider)","CREATE INDEX IF NOT EXISTS idx_uh_ts_model ON usageHistory(timestamp DESC, model)","CREATE INDEX IF NOT EXISTS idx_uh_ts_conn ON usageHistory(timestamp DESC, connectionId)","CREATE INDEX IF NOT EXISTS idx_uh_ts_endpoint ON usageHistory(timestamp DESC, endpoint)","CREATE INDEX IF NOT EXISTS idx_uh_ts_apikey ON usageHistory(timestamp DESC, apiKey)","CREATE INDEX IF NOT EXISTS idx_uh_provider_model_ts ON usageHistory(provider, model, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_status_ts ON usageHistory(status, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_endpoint_ts ON usageHistory(endpoint, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_apikey_ts ON usageHistory(apiKey, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_conn_ts ON usageHistory(connectionId, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_request_id ON usageHistory(requestId)","CREATE INDEX IF NOT EXISTS idx_uh_apikey_id_ts ON usageHistory(apiKeyId, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_apikey_fp_ts ON usageHistory(apiKeyFingerprint, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_ip_ts ON usageHistory(clientIpNormalized, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_tool_ts ON usageHistory(sourceTool, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_session_ts ON usageHistory(sessionId, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_status_code_ts ON usageHistory(statusCode, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_error_type_ts ON usageHistory(errorType, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_uh_latency_ts ON usageHistory(timestamp DESC, latencyMs)","CREATE INDEX IF NOT EXISTS idx_uh_combo_ts ON usageHistory(isCombo, comboName, timestamp DESC)"]},usageHourlyRollup:{columns:{bucket:"TEXT NOT NULL",dimension:"TEXT NOT NULL",key:"TEXT NOT NULL",requests:"INTEGER DEFAULT 0",success:"INTEGER DEFAULT 0",errors:"INTEGER DEFAULT 0",promptTokens:"INTEGER DEFAULT 0",completionTokens:"INTEGER DEFAULT 0",totalTokens:"INTEGER DEFAULT 0",cachedTokens:"INTEGER DEFAULT 0",reasoningTokens:"INTEGER DEFAULT 0",cost:"REAL DEFAULT 0",lastSeen:"TEXT"},primaryKey:"PRIMARY KEY (bucket, dimension, key)",indexes:["CREATE INDEX IF NOT EXISTS idx_uhr_dim_bucket ON usageHourlyRollup(dimension, bucket DESC)","CREATE INDEX IF NOT EXISTS idx_uhr_bucket ON usageHourlyRollup(bucket DESC)"]},usageDailyRollup:{columns:{bucket:"TEXT NOT NULL",dimension:"TEXT NOT NULL",key:"TEXT NOT NULL",requests:"INTEGER DEFAULT 0",success:"INTEGER DEFAULT 0",errors:"INTEGER DEFAULT 0",promptTokens:"INTEGER DEFAULT 0",completionTokens:"INTEGER DEFAULT 0",totalTokens:"INTEGER DEFAULT 0",cachedTokens:"INTEGER DEFAULT 0",reasoningTokens:"INTEGER DEFAULT 0",cost:"REAL DEFAULT 0",lastSeen:"TEXT"},primaryKey:"PRIMARY KEY (bucket, dimension, key)",indexes:["CREATE INDEX IF NOT EXISTS idx_udr_dim_bucket ON usageDailyRollup(dimension, bucket DESC)","CREATE INDEX IF NOT EXISTS idx_udr_bucket ON usageDailyRollup(bucket DESC)"]},usageDaily:{columns:{dateKey:"TEXT PRIMARY KEY",data:"TEXT NOT NULL"}},requestDetails:{columns:{id:"TEXT PRIMARY KEY",timestamp:"TEXT NOT NULL",provider:"TEXT",model:"TEXT",connectionId:"TEXT",status:"TEXT",data:"TEXT NOT NULL"},indexes:["CREATE INDEX IF NOT EXISTS idx_rd_ts ON requestDetails(timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_rd_provider ON requestDetails(provider)","CREATE INDEX IF NOT EXISTS idx_rd_model ON requestDetails(model)","CREATE INDEX IF NOT EXISTS idx_rd_conn ON requestDetails(connectionId)"]}};function f(a,b){let c=Object.entries(b.columns).map(([a,b])=>`${a} ${b}`);return b.primaryKey&&c.push(b.primaryKey),`CREATE TABLE IF NOT EXISTS ${a} (${c.join(", ")})`}}};