// Home Studio 分层存储:localStorage <80KB 热窗+冷折叠 + 异步 IndexedDB 全量账本 (function (G) { 'use strict'; if (!G) return; const LS_CHAR_BUDGET = 72000, COLD_PREFIX = '__ag_cold__:', IDB_STORE = 'scopes'; const K = 'calls,total,input,output,cacheRead,cacheWrite'.split(','), O = Object; const ok = (k) => k && !/^(?:__proto__|constructor|prototype)$/.test(k); const ks = (o) => (o ? O.keys(o).filter(ok) : []); const tn = (v) => { const n = typeof v === 'number' || typeof v === 'bigint' || typeof v === 'string' ? Number(v) : 0; return Number.isFinite(n) ? n : 0; }; const isColdId = (id, r) => !!(r?._cold || (typeof id === 'string' && id.startsWith(COLD_PREFIX))); const getLs = () => (typeof localStorage < 'u' && localStorage) || G.localStorage || null; const getIdb = () => { try { return (typeof indexedDB < 'u' && indexedDB) || G.indexedDB || null; } catch { return null; } }; const addTok = (d, s) => { for (let i = 0, k, v; i < 6; i++) if ((v = tn(s?.[k = K[i]])) > 0 || i < 2) d[k] = (d[k] || 0) + v; }; const addMH = (d, s) => { for (const k of ks(s.hours)) { const h = +k, v = tn(s.hours[k]); if (h >= 0 && h < 24 && v > 0) (d.hours ||= {})[h] = (d.hours[h] || 0) + v; } for (const mk of ks(s.models)) if (s.models[mk]) addTok((d.models ||= {})[mk] ||= { calls: 0, total: 0 }, s.models[mk]); }; const mergeDay = (days, dk, s, mhOnly, slim) => { if (!s || typeof s !== 'object' || !ok(dk)) return; const d = days[dk] ||= { calls: 0, total: 0 }; if (!mhOnly) addTok(d, s); if (!slim) addMH(d, s); }; const compactRecord = (id, r) => { if (!r?.days) return null; const o = { ...r, cascadeId: String(r.cascadeId || id || ''), lastModifiedSec: tn(r.lastModifiedSec), days: {} }; for (const k of O.keys(o)) { const v = o[k]; if (!ok(k) || v === undefined || ((k === 'dbMtimeSec' || k === 'dbSize') && tn(v) <= 0)) delete o[k]; else if (typeof v === 'bigint') o[k] = tn(v); } for (const dk of ks(r.days)) mergeDay(o.days, dk, r.days[dk]); return o; }; const buildTieredLocalPayload = (map, opts = {}) => { const maxR = Math.max(1, tn(opts.maxRecords) || 1200), hotMax = Math.max(1, tn(opts.hotMax) || 120), budget = Math.max(4096, tn(opts.charBudget) || LS_CHAR_BUDGET); const real = [], coldIn = []; for (const e of map instanceof Map ? map : O.entries(map || {})) if (ok(e[0]) && e[1]?.days) (isColdId(e[0], e[1]) ? coldIn : real).push(e); real.sort((a, b) => tn(b[1].lastModifiedSec) - tn(a[1].lastModifiedSec)); const fullEntries = real.slice(0, maxR).map(([id, r]) => [id, compactRecord(id, r)]), evictedIds = real.slice(maxR).map((e) => e[0]); const now = Date.now(), cut = new Date(now - 185 * 864e5).toISOString().slice(0, 10), cut30 = new Date(now - 32 * 864e5).toISOString().slice(0, 10); let json = '{}', hotCount = 0, coldCount = 0; const addC = (cm, r, cCut, mWs, slimOld) => { const ws = mWs ? '' : String(r.workspace || ''), arch = !!r.archived, sub = !!r.subagent, bk = `${ws}\0${+arch}\0${+sub}`; let b = cm.get(bk); if (!b) cm.set(bk, b = { cascadeId: COLD_PREFIX + cm.size, lastModifiedSec: 0, subagent: sub, workspace: ws, calls: 0, days: {}, _cold: 1, _sc: 0, ...(arch ? { archived: true } : null) }); b.lastModifiedSec = Math.max(b.lastModifiedSec, tn(r.lastModifiedSec)); b._sc += r._cold ? Math.max(1, tn(r._sc || 1)) : 1; b.calls += tn(r.calls); for (const dk of ks(r.days)) { if (cCut && dk < cCut) mergeDay(b.days, '1970-01-01', r.days[dk]); else if (slimOld && dk < cut30) { mergeDay(b.days, dk, r.days[dk], 0, 1); mergeDay(b.days, '1970-01-01', r.days[dk], 1, 0); } else mergeDay(b.days, dk, r.days[dk]); } }; for (const t of [hotMax, 48, 16, 4, 0, -1]) { const tk = Math.min(Math.max(0, t), fullEntries.length), out = {}, cm = new Map(), cCut = t < 0 ? '9999' : t < hotMax ? cut : '', mWs = t <= 4, slimOld = t >= 0 && t < hotMax; for (let i = 0; i < fullEntries.length; i++) { const e = fullEntries[i]; i < tk ? (out[e[0]] = e[1]) : addC(cm, e[1], cCut, mWs, slimOld); } for (const e of coldIn) addC(cm, e[1], cCut, mWs, slimOld); for (const b of cm.values()) out[b.cascadeId] = b; hotCount = tk; coldCount = cm.size; if ((json = JSON.stringify(out)).length <= budget) break; } return { json, fullEntries, evictedIds, hotCount, coldCount, hasColdBuckets: coldIn.length > 0 || coldCount > 0 }; }; let dbP = null; const idbOp = async (key, full) => { const idb = getIdb(), rw = !!full, fb = rw ? false : null; if (!idb?.open) return fb; const db = await (dbP ||= new Promise((ok) => { try { const q = idb.open('ag-prism-usage-v1', 1); q.onupgradeneeded = () => { try { q.result.objectStoreNames?.contains?.(IDB_STORE) || q.result.createObjectStore(IDB_STORE); } catch {} }; q.onsuccess = () => ok(q.result || null); q.onerror = () => ok(dbP = null); } catch { ok(dbP = null); } })); return db ? new Promise((ok) => { try { const tx = db.transaction(IDB_STORE, rw ? 'readwrite' : 'readonly'), st = tx.objectStore(IDB_STORE), k = String(key || ''); if (rw) { st.put({ v: 1, records: O.fromEntries(full) }, k); tx.oncomplete = () => ok(true); tx.onerror = tx.onabort = () => ok(false); } else { const q = st.get(k); q.onsuccess = () => ok(q.result?.records || null); q.onerror = () => ok(null); } } catch { ok(fb); } }) : fb; }; const createScopeCacheStore = (recs, scopeKey, fixRec, hasReal, isDead, onHyd) => { let dirty = false, healed = false, hasCold = false, seq = 0, tm = 0, idle = 0; const x = () => { if (tm) tm = (G.clearTimeout?.(tm), 0); if (idle) { try { G.cancelIdleCallback?.(idle); } catch {} idle = 0; } }; const dropCold = () => { if (!hasCold) return false; for (const [k, v] of recs) if (isColdId(k, v)) recs.delete(k); return !(hasCold = false); }; const f = (sc, blk, lf) => { x(); if ((sc === 'local' && blk) || (!recs.size && !lf) || (!dirty && !healed)) return false; try { const ls = getLs(), k = ls && scopeKey(sc); if (!k) return false; const p = buildTieredLocalPayload(recs); for (const id of p.evictedIds) recs.delete(id); ls.setItem(k, p.json); dirty = healed = false; if (!hasCold && p.fullEntries.length && getIdb()) void idbOp(k, p.fullEntries); return true; } catch { return false; } }; return { x, f, m: () => { dirty = true; }, h: () => healed, d: () => dirty, n: () => { let n = 0; for (const [k, r] of recs) n += isColdId(k, r) ? Math.max(1, tn(r?._sc || 1)) : 1; return n; }, l: (sc, getSc) => { recs.clear(); dirty = healed = hasCold = false; const k = scopeKey(sc); try { const s = getLs()?.getItem(k), raw = s && JSON.parse(s); if (raw && typeof raw === 'object') { for (const id of ks(raw)) { const r = raw[id]; if (!r?.days) continue; const c = isColdId(id, r), cr = c ? r : fixRec(id, r); if (c) hasCold = true; else if (cr !== r) healed = true; recs.set(id, cr); } if (s.length > LS_CHAR_BUDGET) dirty = true; } } catch {} if (getIdb()) { const q = ++seq; void idbOp(k).then((ir) => { if (isDead() || q !== seq || getSc() !== sc || !ir) return; let chg = 0; for (const id of ks(ir)) { const raw = ir[id]; if (!raw?.days || isColdId(id, raw)) continue; if (!chg) chg = dropCold() ? 2 : 1; const cr = fixRec(id, raw), cur = recs.get(id); if (!cur || (!hasReal(cur) && hasReal(cr)) || tn(cr.lastModifiedSec) > tn(cur.lastModifiedSec)) { recs.set(id, cr); chg = 2; } } if (chg > 1) onHyd?.(); }).catch(() => {}); } return recs.size > 0; }, s: (getSt) => { const s0 = getSt(); if (s0[0] === 'local' && s0[1]) return; if (isDead() || typeof G.setTimeout !== 'function') return f(...s0); x(); tm = G.setTimeout(() => { tm = 0; const r = () => { idle = 0; if (!isDead()) f(...getSt()); }; if (!isDead()) idle = G.requestIdleCallback ? G.requestIdleCallback(r, { timeout: 2500 }) : (r(), 0); }, 1200); }, c: (bRecs) => { if (!hasCold || !bRecs?.length) return false; let mx = 0; for (const [k, v] of recs) if (isColdId(k, v)) mx = Math.max(mx, tn(v.lastModifiedSec)); return bRecs.some((h) => h?.archived || (h?.record?.days && mx > 0 && tn(h.record.lastModifiedSec) <= mx)) && dropCold() ? (dirty = true) : false; }, }; }; const pub = { isColdId, createScopeCacheStore }; if (typeof module === 'object' && module.exports) module.exports = { ...pub, LS_CHAR_BUDGET, COLD_PREFIX, compactRecord, buildTieredLocalPayload, idbReadScope: (k) => idbOp(k), idbWriteScope: (k, full) => idbOp(k, full || []), resetIdbHandle: () => { dbP = null; } }; G.__agPrismHomeStorage = pub; })(typeof globalThis < 'u' ? globalThis : window);