import{a as e}from"./bG-fsHMS.js";import{r as t,t as n}from"./Ouh6Dj2I2.js";var r=2e3,i=.3,a=.5,o=!1;function s(){let t=e();if(!t)throw Error(`session-narrative: brain.db native handle not available. Call getBrainDb() at startup to initialise the database.`);return o||=(t.exec(`
      CREATE TABLE IF NOT EXISTS session_narrative (
        session_id      TEXT PRIMARY KEY,
        narrative       TEXT NOT NULL DEFAULT '',
        turn_count      INTEGER NOT NULL DEFAULT 0,
        last_updated_at INTEGER NOT NULL DEFAULT 0,
        pivot_count     INTEGER NOT NULL DEFAULT 0
      );
    `),!0),t}function c(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=(e[a]??0)*(t[a]??0),r+=(e[a]??0)**2,i+=(t[a]??0)**2;let a=Math.sqrt(r)*Math.sqrt(i);return a===0?0:n/a}async function l(e){let t=s().prepare(`SELECT session_id, narrative, turn_count, last_updated_at, pivot_count FROM session_narrative WHERE session_id = ?`).get(e);return t?{sessionId:t.session_id,narrative:t.narrative,turnCount:t.turn_count,lastUpdatedAt:t.last_updated_at,pivotCount:t.pivot_count}:null}async function u(e,t,n){if(!t.trim())return;let i=s(),a=Date.now(),o=await l(e),c,u;if(!o)c=t.slice(0,r),u=0;else{let e=await d(t,o.narrative);u=o.pivotCount+ +!!e;let n=o.narrative?`${o.narrative} ${t}`:t;c=n.length<=r?n:n.slice(n.length-r)}let f=(o?.turnCount??0)+1;i.prepare(`
    INSERT INTO session_narrative (session_id, narrative, turn_count, last_updated_at, pivot_count)
    VALUES (?, ?, ?, ?, ?)
    ON CONFLICT(session_id) DO UPDATE SET
      narrative       = excluded.narrative,
      turn_count      = excluded.turn_count,
      last_updated_at = excluded.last_updated_at,
      pivot_count     = excluded.pivot_count
  `).run(e,c,f,a,u)}async function d(e,r){if(!r.trim())return!1;if(t()){let[t,a]=await Promise.all([n(e),n(r)]);if(t!==null&&a!==null)return c(t,a)<i}let o=e=>{let t=e.toLowerCase().split(/\W+/).filter(e=>e.length>=4);return new Set(t)},s=o(e);if(s.size<5)return!1;let l=o(r),u=0;for(let e of s)l.has(e)&&u++;return u/s.size<a}export{l as a,d as i,u as n,c as r,i as t};