@vpxa/aikit 0.1.305 → 0.1.306
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/packages/analyzers/dist/index.js +7 -7
- package/packages/blocks-core/dist/index.mjs +3 -2
- package/packages/cli/dist/index.js +19 -19
- package/packages/indexer/dist/index.js +1 -1
- package/packages/present/dist/index.html +3 -2
- package/packages/server/dist/auth-7LFAZQBu.js +1 -0
- package/packages/server/dist/auth-bEP-6uqy.js +2 -0
- package/packages/server/dist/bin.js +6 -6
- package/packages/server/dist/config-B-wvmMyo.js +1 -0
- package/packages/server/dist/config-Bx85fwRX.js +2 -0
- package/packages/server/dist/{curated-manager-i5QA4c79.js → curated-manager-BrgM_znO.js} +4 -4
- package/packages/server/dist/dashboard-static-Dw7Nsq4f.js +1 -0
- package/packages/server/dist/dashboard-static-dPnij4uF.js +2 -0
- package/packages/server/dist/index.d.ts +97 -88
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{promotion-DmwIVl0c.js → promotion-BGWhzk_I.js} +2 -2
- package/packages/server/dist/{promotion-bQutAIz-.js → promotion-RbjKfC88.js} +2 -2
- package/packages/server/dist/proxy.js +1 -1
- package/packages/server/dist/resolve-sibling-BmZ7AxaA.js +1 -0
- package/packages/server/dist/resolve-sibling-DrGKPpb0.js +2 -0
- package/packages/server/dist/{routes-1wkXLxXe.js → routes-C7bDyCOW.js} +2 -2
- package/packages/server/dist/{routes-KC-D2U8n.js → routes-CfG5gdSR.js} +2 -2
- package/packages/server/dist/{server-0bgaP0Re.js → server-B_KbLM43.js} +177 -175
- package/packages/server/dist/server-http-B-TDT3t-.js +2 -0
- package/packages/server/dist/server-http-BbuuthEP.js +1 -0
- package/packages/server/dist/server-stdio-BUb39kqq.js +2 -0
- package/packages/server/dist/server-stdio-Ch7yAxNk.js +1 -0
- package/packages/server/dist/{server-DQvOpYNO.js → server-utMi-Qu3.js} +177 -175
- package/packages/server/dist/server-utils-De-aZNQa.js +1 -0
- package/packages/server/dist/settings-static-BpQgaMRs.js +1 -0
- package/packages/server/dist/settings-static-MepJZjer.js +2 -0
- package/packages/server/dist/startup-maintenance-D0Uhpi3k.js +1 -0
- package/packages/server/dist/startup-maintenance-L9NUOBVy.js +2 -0
- package/packages/server/dist/version-check-6qDKknz4.js +1 -0
- package/packages/server/dist/version-check-DSWaugPC.js +2 -0
- package/packages/server/dist/workspace-bootstrap-BPWA6BVf.js +1 -0
- package/packages/server/viewers/canvas.html +3 -2
- package/packages/server/viewers/report-template.html +3 -2
- package/packages/server/viewers/tour-viewer.html +3 -2
- package/packages/store/dist/index.d.ts +3 -1
- package/packages/store/dist/index.js +24 -24
- package/scaffold/dist/adapters/hermes-agent.mjs +56 -0
- package/scaffold/dist/definitions/models.mjs +1 -1
- package/scaffold/dist/definitions/skills/c4-architecture.mjs +1 -1
- package/scaffold/dist/definitions/skills/docs.mjs +1 -1
- package/scaffold/dist/definitions/skills/present.mjs +1 -1
- package/scaffold/dist/generated/block-docs.mjs +13 -2
- package/packages/server/dist/auth-Bz5dmZgR.js +0 -1
- package/packages/server/dist/auth-lzZKfxlV.js +0 -2
- package/packages/server/dist/config-CaJwUDXI.js +0 -2
- package/packages/server/dist/config-_gMeJYrz.js +0 -1
- package/packages/server/dist/dashboard-static-CRfR1yKU.js +0 -2
- package/packages/server/dist/dashboard-static-FmfoS46e.js +0 -1
- package/packages/server/dist/resolve-sibling-1oDoO-Re.js +0 -1
- package/packages/server/dist/resolve-sibling-ByoHo7Tp.js +0 -2
- package/packages/server/dist/settings-static-B3lnYvcb.js +0 -2
- package/packages/server/dist/settings-static-BtvyIrza.js +0 -1
- package/packages/server/dist/version-check-CJK1Fwmy.js +0 -2
- package/packages/server/dist/version-check-yzdUDXHC.js +0 -1
|
@@ -54,8 +54,9 @@
|
|
|
54
54
|
.bk-form fieldset { border: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: var(--dt-space-3); }
|
|
55
55
|
.bk-form-field { display: flex; flex-direction: column; gap: var(--dt-space-1); }
|
|
56
56
|
.bk-form-label { font-size: 0.875rem; font-weight: 500; color: var(--dt-text-secondary); }
|
|
57
|
-
|
|
58
|
-
|
|
57
|
+
.bk-action-feedback { font-size: 0.875rem; color: var(--dt-text-secondary); padding: var(--dt-space-2) 0; }
|
|
58
|
+
.bk-action-feedback[data-feedback-state="sent"] { color: var(--dt-success-fg, #16a34a); }
|
|
59
|
+
`;function f(t,r){return`<div class="bk-actions">${u(t.value).map(t=>{let r=n(t.id);if(t.type===`select`){let n=(t.options??[]).map(t=>{let n=typeof t==`string`?t:t.value,r=typeof t==`string`?t:t.label;return`<option value="${e(n)}">${e(r)}</option>`}).join(``);return`<label class="bk-select-wrap"><span class="bk-visually-hidden">${e(t.label)}</span><select class="bk-select" data-action-id="${r}"><option value="" selected disabled>${e(t.label)}</option>${n}</select></label>`}if(t.type===`text-submit`)return`<div class="bk-text-submit" data-action-id="${r}"><input type="text" class="bk-input" placeholder="${e(t.label)}" data-action-id="${r}" /><button type="button" class="bk-action bk-action--primary" data-action-id="${r}">Send</button></div>`;if(t.type===`form-submit`&&t.schema){let n=t.schema;return`<form class="bk-form" data-action-id="${r}"><fieldset>${Object.entries(n).map(([t,n])=>{let r=n.description??t,i=n.type===`number`?`number`:`text`;return`<label class="bk-form-field"><span class="bk-form-label">${e(r)}</span><input type="${i}" class="bk-input" name="${e(t)}" placeholder="${e(r)}" /></label>`}).join(``)}<button type="submit" class="bk-action bk-action--primary">${e(t.label)}</button></fieldset></form>`}return`<button type="button" class="bk-action bk-action--${e(t.variant??`default`)}" data-action-id="${r}">${e(t.label)}</button>`}).join(``)}<div class="bk-action-feedback" style="display:none;font-size:0.875rem;color:var(--dt-text-secondary);padding:var(--dt-space-2) 0;" data-feedback-state="pending">💬 Feedback sent</div></div>`}var p=`
|
|
59
60
|
.bk-cards {
|
|
60
61
|
display: grid;
|
|
61
62
|
grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr));
|
|
@@ -65,8 +65,9 @@ Error generating stack: `+e.message+`
|
|
|
65
65
|
.bk-form fieldset { border: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: var(--dt-space-3); }
|
|
66
66
|
.bk-form-field { display: flex; flex-direction: column; gap: var(--dt-space-1); }
|
|
67
67
|
.bk-form-label { font-size: 0.875rem; font-weight: 500; color: var(--dt-text-secondary); }
|
|
68
|
-
|
|
69
|
-
|
|
68
|
+
.bk-action-feedback { font-size: 0.875rem; color: var(--dt-text-secondary); padding: var(--dt-space-2) 0; }
|
|
69
|
+
.bk-action-feedback[data-feedback-state="sent"] { color: var(--dt-success-fg, #16a34a); }
|
|
70
|
+
`;function k(e,t){return`<div class="bk-actions">${D(e.value).map(e=>{let t=y(e.id);if(e.type===`select`){let n=(e.options??[]).map(e=>{let t=typeof e==`string`?e:e.value,n=typeof e==`string`?e:e.label;return`<option value="${_(t)}">${_(n)}</option>`}).join(``);return`<label class="bk-select-wrap"><span class="bk-visually-hidden">${_(e.label)}</span><select class="bk-select" data-action-id="${t}"><option value="" selected disabled>${_(e.label)}</option>${n}</select></label>`}if(e.type===`text-submit`)return`<div class="bk-text-submit" data-action-id="${t}"><input type="text" class="bk-input" placeholder="${_(e.label)}" data-action-id="${t}" /><button type="button" class="bk-action bk-action--primary" data-action-id="${t}">Send</button></div>`;if(e.type===`form-submit`&&e.schema){let n=e.schema;return`<form class="bk-form" data-action-id="${t}"><fieldset>${Object.entries(n).map(([e,t])=>{let n=t.description??e,r=t.type===`number`?`number`:`text`;return`<label class="bk-form-field"><span class="bk-form-label">${_(n)}</span><input type="${r}" class="bk-input" name="${_(e)}" placeholder="${_(n)}" /></label>`}).join(``)}<button type="submit" class="bk-action bk-action--primary">${_(e.label)}</button></fieldset></form>`}return`<button type="button" class="bk-action bk-action--${_(e.variant??`default`)}" data-action-id="${t}">${_(e.label)}</button>`}).join(``)}<div class="bk-action-feedback" style="display:none;font-size:0.875rem;color:var(--dt-text-secondary);padding:var(--dt-space-2) 0;" data-feedback-state="pending">💬 Feedback sent</div></div>`}var A=`
|
|
70
71
|
.bk-cards {
|
|
71
72
|
display: grid;
|
|
72
73
|
grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr));
|
|
@@ -436,11 +436,13 @@ declare class SqliteVecStore implements IKnowledgeStore {
|
|
|
436
436
|
private vectorEnabled;
|
|
437
437
|
private ftsEnabled;
|
|
438
438
|
private warnedVectorDisabled;
|
|
439
|
-
private
|
|
439
|
+
private _drainState;
|
|
440
440
|
private _priorityQueue;
|
|
441
441
|
private _normalQueue;
|
|
442
442
|
private _closeWaiter;
|
|
443
443
|
private _onCloseHooks;
|
|
444
|
+
/** Set to true at the start of close() to reject any new enqueueWrite calls. */
|
|
445
|
+
private _closing;
|
|
444
446
|
constructor(options?: SqliteVecStoreOptions);
|
|
445
447
|
initialize(): Promise<void>;
|
|
446
448
|
private configureConnectionPragmas;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DEFAULTS as n,SEARCH_DEFAULTS as r,STORE_DEFAULTS as i,createLogger as a,serializeError as o,sourceTypeContentTypes as s}from"../../core/dist/index.js";import{existsSync as c,mkdirSync as l,readFileSync as u,renameSync as d,unlinkSync as f,writeFileSync as p}from"node:fs";import{basename as
|
|
1
|
+
import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DEFAULTS as n,SEARCH_DEFAULTS as r,STORE_DEFAULTS as i,createLogger as a,serializeError as o,sourceTypeContentTypes as s}from"../../core/dist/index.js";import{existsSync as c,mkdirSync as l,readFileSync as u,renameSync as d,statSync as ee,unlinkSync as f,writeFileSync as p}from"node:fs";import{basename as te,dirname as m,extname as ne,join as h}from"node:path";import{homedir as re}from"node:os";var ie=Object.defineProperty,ae=(e,t)=>{let n={};for(var r in e)ie(n,r,{get:e[r],enumerable:!0});return t||ie(n,Symbol.toStringTag,{value:`Module`}),n};const oe=a(`migrations`);function se(e){e.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS _migrations (
|
|
3
3
|
version INTEGER PRIMARY KEY,
|
|
4
4
|
name TEXT NOT NULL,
|
|
5
5
|
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
6
6
|
)
|
|
7
|
-
`)}function g(e,t){se(e);let n=new Set(e.queryAll(`SELECT version FROM _migrations`).map(e=>e.version)),r=[...t].sort((e,t)=>e.version-t.version).filter(e=>!n.has(e.version));for(let t of r){e.exec(`BEGIN`);try{t.up(e),e.run(`INSERT INTO _migrations (version, name) VALUES (?, ?)`,[t.version,t.name]),e.exec(`COMMIT`)}catch(t){try{e.exec(`ROLLBACK`)}catch{}throw t}}}const _=[{version:1,name:`create state store tables`,up(e){e.exec(`
|
|
7
|
+
`)}function g(e,t){se(e);let n=new Set(e.queryAll(`SELECT version FROM _migrations`).map(e=>e.version)),r=[...t].sort((e,t)=>e.version-t.version).filter(e=>!n.has(e.version));for(let t of r){e.exec(`BEGIN IMMEDIATE`);try{t.up(e),e.run(`INSERT INTO _migrations (version, name) VALUES (?, ?)`,[t.version,t.name]),e.exec(`COMMIT`)}catch(t){try{e.exec(`ROLLBACK`)}catch{}throw t}}}const _=[{version:1,name:`create state store tables`,up(e){e.exec(`
|
|
8
8
|
CREATE TABLE IF NOT EXISTS stash (
|
|
9
9
|
key TEXT PRIMARY KEY,
|
|
10
10
|
value TEXT NOT NULL,
|
|
@@ -111,17 +111,17 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
111
111
|
`)}},{version:4,name:`backfill vec0 embeddings into memory_embeddings`,up(e){let t=e.queryAll(`SELECT COUNT(*) AS cnt FROM memory_embeddings`);if(t[0]?.cnt&&t[0].cnt>0)return;let n=e.queryAll(`SELECT name, sql FROM sqlite_master WHERE type = 'table' AND sql LIKE '%vec0%'`);if(n.length===0)return;let r=Date.now(),i=0;for(let t of n){let n=t.sql.match(/(?:int8|float)\[(\d+)\]/i);if(!n)continue;let a=Number(n[1]),o=e.queryAll(`SELECT COUNT(*) AS cnt FROM memory_embeddings`)[0]?.cnt??0;e.run(`INSERT OR IGNORE INTO memory_embeddings
|
|
112
112
|
(memory_id, embedding_model, embedding_version, dimensions, element_type, embedding, created_at)
|
|
113
113
|
SELECT knowledge_id, 'default', '1', ?, 'float32', embedding, ?
|
|
114
|
-
FROM ${t.name}`,[a,r]);let s=e.queryAll(`SELECT COUNT(*) AS cnt FROM memory_embeddings`)[0]?.cnt??0;i+=s-o}i>0&&oe.info(`[migration v4] backfilled ${i} embeddings into memory_embeddings`)}}],v=a(`sqlite-adapter`),y=e(import.meta.url),b=`better-sqlite3`;function ce(e){return e.replace(/\\/g,`/`)}function x(){return y.resolve(`@vpxa/aikit/package.json`).replace(/[\\/]package\.json$/,``)}function S(){return x().replace(/[\\/]node_modules[\\/]@vpxa[\\/]aikit$/,``)}function le(e){return ce(e).includes(`/_npx/`)}function C(){try{return JSON.parse(u(h(x(),`package.json`),`utf8`)).optionalDependencies?.[b]??`latest`}catch{return`latest`}}function ue(e){return e.replace(/[^a-zA-Z0-9._-]+/g,`_`)}function de(){let e=`${ue(C())}-${process.platform}-${process.arch}-abi${process.versions.modules}`;return h(ne(),`.aikit`,`cache`,`native-modules`,b,e)}function w(e){l(e,{recursive:!0});let t=h(e,`package.json`);c(t)||p(t,`${JSON.stringify({name:`aikit-native-runtime-cache`,private:!0},null,2)}\n`,`utf8`)}function fe(e){let t=E(e);if(!t)return null;try{return JSON.parse(u(h(t,`package.json`),`utf8`)).version??null}catch{return null}}function pe(e,t){try{let n={packageName:b,packageSpec:C(),packageVersion:fe(e),platform:process.platform,arch:process.arch,nodeAbi:process.versions.modules,installedAt:new Date().toISOString(),source:t};p(h(e,`.aikit-native-module.json`),`${JSON.stringify(n,null,2)}\n`,`utf8`)}catch(e){v.debug(`Failed to write better-sqlite3 runtime marker`,o(e))}}var T=class{runtimeRoot;type=`better-sqlite3`;kind=`better-sqlite3`;vectorCapable=!1;get capabilities(){return{vectorCapable:this.vectorCapable,persistentFile:!0,concurrentReaders:!0}}db=null;stmtCache=new Map;dbPath=``;DatabaseCtor=null;recovering=!1;constructor(e){this.runtimeRoot=e}async open(t){let n;try{let t=y;this.runtimeRoot!=null&&(w(this.runtimeRoot),t=e(h(this.runtimeRoot,`package.json`))),n=t(b)}catch(e){throw Error(`better-sqlite3 native binding unavailable: ${e instanceof Error?e.message:String(e)}`)}this.db=new n(t),this.dbPath=t,this.DatabaseCtor=n,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`),this.runIntegrityCheck(t,n)||(this.db?.pragma(`journal_mode = WAL`),this.db?.pragma(`foreign_keys = ON`),this.db?.pragma(`synchronous = NORMAL`));try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0,v.debug(`sqlite-vec extension loaded`)}catch(e){this.vectorCapable=!1,v.warn(`sqlite-vec extension failed to load; vector search disabled`,o(e))}}exec(e){try{this.getDb().exec(e)}catch(t){if(this.isCorruptionError(t)){this.recover(),this.getDb().exec(e);return}throw t}}pragma(e){this.getDb().pragma(e)}queryAll(e,t=[]){try{let n=this.prepareCached(e);return t.length>0?n.all(...t):n.all()}catch(n){if(this.isCorruptionError(n))return this.recover(),this.queryAll(e,t);throw n}}run(e,t){try{let n=this.prepareCached(e);return t===void 0?n.run():Array.isArray(t)?t.length===0?n.run():n.run(...t):n.run(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.run(e,t);throw n}}get(e,t){try{let n=this.prepareCached(e);return t===void 0?n.get():Array.isArray(t)?t.length>0?n.get(...t):n.get():n.get(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.get(e,t);throw n}}all(e,t){try{let n=this.prepareCached(e);return t===void 0?n.all():Array.isArray(t)?t.length>0?n.all(...t):n.all():n.all(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.all(e,t);throw n}}transaction(e){return this.getDb().transaction(()=>e(this.createTransactionHandle()))()}createTransactionHandle(){return{exec:e=>this.exec(e),get:(e,t)=>this.get(e,t),all:(e,t)=>this.all(e,t),run:(e,t)=>this.run(e,t)}}flush(){}async close(){this.db&&=(this.stmtCache.clear(),this.db.close(),null)}runIntegrityCheck(e,t){try{let t=this.db?.pragma(`integrity_check`);if(t.length===1&&t[0]?.integrity_check===`ok`)return!0;let n=t.map(e=>e.integrity_check).slice(0,5).join(`; `);v.warn(`Database integrity check failed — recreating`,{dbPath:e,issues:n})}catch(t){v.warn(`Integrity check query failed — recreating database`,{dbPath:e,error:o(t)})}try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{f(e)}catch{}try{f(`${e}-wal`)}catch{}try{f(`${e}-shm`)}catch{}return this.db=new t(e),v.info(`Database recreated successfully — full reindex required`,{dbPath:e}),!1}isCorruptionError(e){if(this.recovering)return!1;let t=e instanceof Error?e.message:String(e);return/database disk image is malformed|file is not a database|database or disk is full/.test(t)}recover(){if(this.recovering)throw Error(`BetterSqlite3Adapter: recovery already in progress`);this.recovering=!0;try{v.warn(`Runtime corruption detected — recovering database`,{dbPath:this.dbPath});try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{f(this.dbPath)}catch{}try{f(`${this.dbPath}-wal`)}catch{}try{f(`${this.dbPath}-shm`)}catch{}if(!this.DatabaseCtor)throw Error(`DatabaseCtor is not initialized`);this.db=this.DatabaseCtor(this.dbPath),this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`);try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0}catch{this.vectorCapable=!1}v.info(`Database recovered — full reindex required`,{dbPath:this.dbPath})}finally{this.recovering=!1}}getDb(){if(!this.db)throw Error(`BetterSqlite3Adapter: database not opened`);return this.db}prepareCached(e){let t=this.stmtCache.get(e);if(t)return t;let n=this.getDb().prepare(e);return this.stmtCache.set(e,n),n}};function E(e){if(e){let t=h(e,`node_modules`,b);return c(h(t,`package.json`))?t:null}try{return y.resolve(`${b}/package.json`).replace(/[\\/]package\.json$/,``)}catch{return null}}function me(e){let t=E(e);if(!t)return null;let n=h(t,`build`,`Release`,`better_sqlite3.node`);return c(n)?n:null}async function he(e){let t=E(e);if(!t)return`package-missing`;if(!c(h(t,`build`,`Release`,`better_sqlite3.node`)))return`binding-missing`;try{let{execFileSync:t}=await import(`node:child_process`),n=e??S();return e&&w(e),t(process.execPath,[`-e`,`require('${b}')`],{cwd:n,stdio:`pipe`,timeout:15e3,windowsHide:!0}),`ok`}catch(e){let t=e instanceof Error&&`stderr`in e?String(e.stderr):``;return/NODE_MODULE_VERSION/.test(t)?`abi-mismatch`:/Could not locate the bindings file|no native build was found/.test(t)?`binding-missing`:`error`}}async function ge(e,t=!1){let n=E(e);if(!n)return v.info(`better-sqlite3 package is not installed — skipping native rebuild`),!1;try{let{execFileSync:r}=await import(`node:child_process`),i=e??n.replace(/[\\/]node_modules[\\/]better-sqlite3$/,``),a=process.platform===`win32`?`npm.cmd`:`npm`;if(e&&w(e),t){let e=h(n,`build`,`Release`,`better_sqlite3.node`);if(c(e))try{f(e),v.info(`Deleted stale native binding before rebuild`,{path:e})}catch(t){v.warn(`Cannot delete stale native binding — file may be locked by another process`,{path:e,error:t instanceof Error?t.message:String(t)})}}return v.info(`Attempting native module rebuild for better-sqlite3`,{cwd:i}),r(a,[`rebuild`,b],{cwd:i,stdio:`pipe`,timeout:6e4,windowsHide:!0}),v.info(`Native module rebuild completed successfully`),pe(i,`rebuild`),!0}catch(e){return v.warn(`Native module rebuild failed — continuing with sql.js fallback`,o(e)),!1}}async function _e(e){try{let{execFileSync:t}=await import(`node:child_process`),n=e??S(),r=process.platform===`win32`?`npm.cmd`:`npm`,i=C();return w(n),v.info(`Attempting to install better-sqlite3 for native adapter recovery`,{cwd:n,packageSpec:i}),t(r,[`install`,`--no-save`,`--package-lock=false`,`--no-audit`,`--no-fund`,`--omit=dev`,`${b}@${i}`],{cwd:n,stdio:`pipe`,timeout:12e4,windowsHide:!0}),v.info(`better-sqlite3 install completed successfully`),pe(n,`install`),!0}catch(e){return v.warn(`better-sqlite3 install failed — continuing with sql.js fallback`,o(e)),!1}}const D=a(`driver-selector`),O=e(import.meta.url);var ve=class extends Error{code=`STORAGE_INITIALIZATION_FAILED`;failures;constructor(e){let t=e.map(e=>`[${e.code}] ${e.driver}: ${e.message}`).join(`; `);super(`All SQLite drivers failed to initialise (${e.length}): ${t}`),this.name=`StorageInitializationError`,this.failures=e}};function ye(e){let[t,n]=(e??process.versions.node).split(`.`),r=Number.parseInt(t??`0`,10);return r>22||r===22&&Number.parseInt(n??`0`,10)>=13}function be(e){if(typeof e!=`function`)return!1;let t=e.prototype;return typeof t?.enableLoadExtension==`function`&&typeof t.loadExtension==`function`}function k(e,t,n){return{available:!1,failure:{driver:e,code:t,message:n}}}function A(e){return{available:!0,capabilities:e}}function j(){try{try{let e=O(`sqlite-vec`);if(typeof e.getLoadablePath==`function`){let t=e.getLoadablePath();if(t&&c(t))return t}if(e.loadablePath&&c(e.loadablePath))return e.loadablePath}catch{}let e=m(O.resolve(`sqlite-vec/package.json`)),t={"win32-x64":`sqlite-vec-win32-x64.node`,"win32-arm64":`sqlite-vec-win32-arm64.node`,"darwin-x64":`sqlite-vec-darwin-x64.node`,"darwin-arm64":`sqlite-vec-darwin-arm64.node`,"linux-x64":`sqlite-vec-linux-x64.node`,"linux-arm64":`sqlite-vec-linux-arm64.node`}[`${process.platform}-${process.arch}`];if(t){let n=h(e,t);if(c(n))return n}let n=h(e,`sqlite-vec.node`);if(c(n))return n;let r=h(m(O.resolve(`sqlite-vec`)),`sqlite-vec.node`);return c(r)?r:null}catch{return null}}async function M(){if(!ye())return k(`node-sqlite`,`NODE_VERSION_UNSUPPORTED`,`Node.js ${process.versions.node} < 22.13 — node:sqlite extension loading unavailable`);let e;try{let t=await import(`node:sqlite`);if(!be(t.DatabaseSync))return k(`node-sqlite`,`EXTENSION_LOADING_DISABLED`,`node:sqlite is available but DatabaseSync extension loading APIs are unavailable`);e=t.DatabaseSync}catch(e){return k(`node-sqlite`,`MODULE_NOT_AVAILABLE`,`node:sqlite not available: ${e instanceof Error?e.message:String(e)}`)}let t=new e(`:memory:`,{allowExtension:!0});try{try{t.enableLoadExtension(!0)}catch(e){return k(`node-sqlite`,`EXTENSION_LOADING_DISABLED`,`enableLoadExtension failed: ${e instanceof Error?e.message:String(e)}`)}let e=j();if(!e)return k(`node-sqlite`,`NATIVE_BINARY_UNAVAILABLE`,`Could not resolve sqlite-vec native binary path`);try{t.loadExtension(e)}catch(e){return k(`node-sqlite`,`SQLITE_VEC_LOAD_FAILED`,`sqlite-vec loadExtension failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=t.prepare(`SELECT vec_version() AS v`).get();if(!e||typeof e.v!=`string`)return k(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() returned empty result`);D.debug(`node-sqlite: sqlite-vec ${e.v}`)}catch(e){return k(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=new Uint8Array(new Float32Array([1,0,0]).buffer),n=t.prepare(`SELECT vec_distance_cosine(?, ?) AS d`).get(e,e);if(!n||typeof n.d!=`number`)return k(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: unexpected result ${JSON.stringify(n)}`);D.debug(`node-sqlite: vector smoke test passed`)}catch(e){return k(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: ${e instanceof Error?e.message:String(e)}`)}}finally{try{t.enableLoadExtension(!1)}catch{}t.close()}return D.debug(`node:sqlite driver ready (sqlite-vec enabled)`),A({vectorCapable:!0,persistentFile:!0,concurrentReaders:!0})}async function xe(){let e;try{e=O(`better-sqlite3`)}catch(e){return k(`better-sqlite3`,`MODULE_NOT_AVAILABLE`,`better-sqlite3 not available: ${e instanceof Error?e.message:String(e)}`)}let t;try{t=new e(`:memory:`)}catch(e){return k(`better-sqlite3`,`DATABASE_OPEN_FAILED`,`Failed to open in-memory database: ${e instanceof Error?e.message:String(e)}`)}try{try{O(`sqlite-vec`).load(t)}catch(e){return k(`better-sqlite3`,`SQLITE_VEC_LOAD_FAILED`,`sqlite-vec load failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=t.prepare(`SELECT vec_version() AS v`).get();if(!e||typeof e.v!=`string`)return k(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() returned empty result`);D.debug(`better-sqlite3: sqlite-vec ${e.v}`)}catch(e){return k(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=new Uint8Array(new Float32Array([1,0,0]).buffer),n=t.prepare(`SELECT vec_distance_cosine(?, ?) AS d`).get([e,e]);if(!n||typeof n.d!=`number`)return k(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: unexpected result ${JSON.stringify(n)}`);D.debug(`better-sqlite3: vector smoke test passed`)}catch(e){return k(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: ${e instanceof Error?e.message:String(e)}`)}}finally{t.close()}return D.debug(`better-sqlite3 driver ready (sqlite-vec enabled)`),A({vectorCapable:!0,persistentFile:!0,concurrentReaders:!0})}async function Se(){let e;try{let t=await import(`sql.js`);e=t.default??t}catch(e){return k(`sqljs`,`MODULE_NOT_AVAILABLE`,`sql.js module not available: ${e instanceof Error?e.message:String(e)}`)}let t;try{let e=m(O.resolve(`sql.js/package.json`)),n=h(e,`dist`,`sql-wasm.wasm`);c(n)&&(t=t=>t.endsWith(`.wasm`)?n:h(e,`dist`,t))}catch{}let n;try{n=await e(t?{locateFile:t}:void 0)}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`wasm`)||t.includes(`WASM`)||t.includes(`WebAssembly`)?k(`sqljs`,`WASM_INITIALIZATION_FAILED`,`sql.js WASM initialisation failed: ${t}`):k(`sqljs`,`WASM_ASSET_NOT_FOUND`,`sql.js initialisation failed (WASM asset may be missing): ${t}`)}try{new n.Database().close()}catch(e){return k(`sqljs`,`DATABASE_OPEN_FAILED`,`sql.js in-memory database failed: ${e instanceof Error?e.message:String(e)}`)}return D.debug(`sql.js driver ready (vector search disabled)`),A({vectorCapable:!1,persistentFile:!0,concurrentReaders:!1})}async function N(e){let t=e.driver??`auto`;if(t!==`auto`)return Ce(t);let n=[];{let e=await M();if(e.available)return{kind:`node-sqlite`,capabilities:e.capabilities,failures:[]};e.failure&&n.push(e.failure)}{let e=await xe();if(e.available)return{kind:`better-sqlite3`,capabilities:e.capabilities,failures:n};e.failure&&n.push(e.failure)}{let e=await Se();if(e.available)return{kind:`sqljs`,capabilities:e.capabilities,failures:n};e.failure&&n.push(e.failure)}throw new ve(n)}async function Ce(e){let{kind:t,capabilities:n,failures:r}=await we(e);if(!n)throw new ve(r);return{kind:t,capabilities:n,failures:r}}async function we(e){let t=e;switch(e){case`node-sqlite`:{let e=await M();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}case`better-sqlite3`:{let e=await xe();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}case`sqljs`:{let e=await Se();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}default:throw Error(`Unreachable: unknown driver mode "${e}"`)}}const Te=e(import.meta.url),Ee=a(`sqljs-adapter`);function De(e){return Te.resolve(`sql.js/dist/${e}`)}function Oe(e){return e.match(/^\s*(?:INSERT(?:\s+OR\s+\w+)?\s+INTO|UPDATE)\s+([A-Za-z_][A-Za-z0-9_]*)/i)?.[1]??null}var P=class{type=`sql.js`;kind=`sqljs`;vectorCapable=!1;capabilities={vectorCapable:!1,persistentFile:!0,concurrentReaders:!1};db=null;dbPath=``;dirty=!1;flushTimer=null;DEBOUNCE_MS=1e3;MAX_DB_SIZE_BYTES=500*1024*1024;inTransaction=!1;foreignKeysEnabled=!1;async open(e){this.dbPath=e;let t=(await import(`sql.js`)).default,n=await t({locateFile:e=>De(e)});if(c(e)){let t=u(e);this.db=new n.Database(t)}else this.db=new n.Database}exec(e){let t=e.trimStart().toUpperCase();this.getDb().run(e),t.startsWith(`BEGIN`)?this.inTransaction=!0:(t.startsWith(`COMMIT`)||t.startsWith(`ROLLBACK`))&&(this.inTransaction=!1),this.markDirty()}pragma(e){let t=e.trim().toLowerCase();t===`foreign_keys = on`||t===`foreign_keys=on`?this.foreignKeysEnabled=!0:(t===`foreign_keys = off`||t===`foreign_keys=off`)&&(this.foreignKeysEnabled=!1),this.getDb().exec(`PRAGMA ${e}`)}queryAll(e,t=[]){let n=this.getDb().prepare(e);try{t.length>0&&n.bind(t);let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}execWrite(e,t){let n=this.getDb();if(t===void 0){n.run(e);return}let r=n.prepare(e);try{r.bind(t),r.step()}finally{r.free()}}toBindParams(e){if(e!==void 0)return Array.isArray(e)&&e.length===0?void 0:e}run(e,t){let n=this.getDb(),r=e.trimStart().toUpperCase(),i=Oe(e),a=this.foreignKeysEnabled&&!this.inTransaction&&i!==null&&(r.startsWith(`INSERT`)||r.startsWith(`UPDATE`));a&&n.run(`SAVEPOINT fk_check`);try{if(this.execWrite(e,this.toBindParams(t)),a){if(n.exec(`PRAGMA foreign_key_check(${i})`).length>0)throw n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`),Error(`FOREIGN KEY constraint failed`);n.run(`RELEASE fk_check`)}}catch(e){if(a)try{n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`)}catch{}throw e}return this.markDirty(),this.getChangesResult(n)}getChangesResult(e){let t=e.exec(`SELECT changes() AS changes, last_insert_rowid() AS rowid`),n=t[0]?.values[0]?.[0]??0,r=t[0]?.values[0]?.[1];return{changes:Number(n),lastInsertRowid:r===void 0?void 0:Number(r)}}get(e,t){let n=this.getDb().prepare(e);try{return t!==void 0&&(Array.isArray(t)?t.length>0&&n.bind(t):n.bind(t)),n.step()?n.getAsObject():void 0}finally{n.free()}}all(e,t){let n=this.getDb().prepare(e);try{t!==void 0&&(Array.isArray(t)?t.length>0&&n.bind(t):n.bind(t));let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}transaction(e){this.exec(`BEGIN IMMEDIATE`);try{let t=e(this.createTransactionHandle());return this.exec(`COMMIT`),t}catch(e){throw this.exec(`ROLLBACK`),e}}createTransactionHandle(){return{exec:e=>this.exec(e),get:(e,t)=>this.get(e,t),all:(e,t)=>this.all(e,t),run:(e,t)=>this.run(e,t)}}markDirty(e=!1){this.dirty=!0,e?this.flushImmediate():this.scheduleFlush()}scheduleFlush(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush()},this.DEBOUNCE_MS),this.flushTimer&&typeof this.flushTimer==`object`&&`unref`in this.flushTimer&&this.flushTimer.unref()}flushImmediate(){this.flushTimer&&=(clearTimeout(this.flushTimer),null),this.flush()}notifyCriticalWrite(){this.flushImmediate()}flush(){if(!this.dirty||!this.db)return;let e=this.db.export();e.byteLength>this.MAX_DB_SIZE_BYTES&&Ee.warn(`Database size ${e.byteLength} bytes exceeds guardrail ${this.MAX_DB_SIZE_BYTES} bytes`);let t=`${this.dbPath}.tmp`,n=m(this.dbPath);n&&!c(n)&&l(n,{recursive:!0}),p(t,Buffer.from(e));try{f(this.dbPath)}catch{}d(t,this.dbPath),this.dirty=!1}async close(){if(this.flushTimer&&=(clearTimeout(this.flushTimer),null),this.db){let e=this.db,t;if(this.dirty)try{this.flush()}catch(e){t=e;try{f(`${this.dbPath}.tmp`)}catch{}}try{e.close()}finally{this.db=null}if(t)throw t}}getDb(){if(!this.db)throw Error(`SqlJsAdapter: database not opened`);return this.db}};const F=a(`sqlite-adapter`);e(import.meta.url);function ke(){return!!process.env.VITEST||process.argv.some(e=>e.includes(`vitest`))}async function Ae(){let e=L.resolveAikitRuntimeRoot(),t=await L.probeNativeModuleAbi(e);if(t===`ok`)return e;if(L.isNpxRuntimeRoot(e)){let e=L.resolvePersistentNativeRuntimeRoot(),t=await L.probeNativeModuleAbi(e);if(t===`ok`)return F.info(`Using cached better-sqlite3 native runtime`,{runtimeRoot:e,version:L.resolveNativeModuleVersion(e)}),e;let n=!1;if(t===`abi-mismatch`?(F.info(`Persistent better-sqlite3 cache ABI mismatch — rebuilding cached binding`),n=await L.tryRebuildNativeModule(e,!0)):t===`binding-missing`?(F.info(`Persistent better-sqlite3 cache missing binding — rebuilding cache`),n=await L.tryRebuildNativeModule(e,!1)):(F.info(`Persistent better-sqlite3 cache missing — installing cached runtime`,{runtimeRoot:e,packageSpec:L.readAikitPackageSpec()}),n=await L.tryInstallNativeModule(e)),n&&await L.probeNativeModuleAbi(e)===`ok`)return F.info(`Persistent better-sqlite3 cache ready`,{runtimeRoot:e,version:L.resolveNativeModuleVersion(e)}),e}if(t===`abi-mismatch`){if(F.info(`Detected NODE_MODULE_VERSION mismatch via pre-flight probe — rebuilding before load`),await L.tryRebuildNativeModule(e,!0)&&await L.probeNativeModuleAbi(e)===`ok`)return F.info(`Pre-flight rebuild succeeded — proceeding with native adapter`),e}else if(t===`binding-missing`){if(F.info(`No native binding found — attempting rebuild before load`),await L.tryRebuildNativeModule(e,!1)&&await L.probeNativeModuleAbi(e)===`ok`)return e}else if(t===`package-missing`&&(F.info(`better-sqlite3 package is not installed — attempting install before load`),await L.tryInstallNativeModule(e)&&await L.probeNativeModuleAbi(e)===`ok`))return e;return null}async function I(e){let t=await N({driver:process.env.AI_KIT_SQLITE_DRIVER??`auto`,databasePath:e});F.debug(`Storage backend: ${t.kind}`);for(let e of t.failures)F.warn(` ${e.driver}: ${e.code} — ${e.message}`);switch(t.kind){case`node-sqlite`:{let{NodeSqliteAdapter:t}=await Promise.resolve().then(()=>mt),n=new t;return await n.open(e),n}case`better-sqlite3`:{if(!L.isVitestRuntime()){let t=await L.preparePreferredNativeRuntime(),n=L.createNativeAdapter(t??void 0);try{return await n.open(e),n}catch(n){let r=n instanceof Error?n.message:String(n);if(!L.isVitestRuntime()&&/NODE_MODULE_VERSION|Could not locate the bindings file|no native build was found/.test(r)){let n=t??L.resolveAikitRuntimeRoot();if(await L.tryRebuildNativeModule(n,!1)){let t=L.createNativeAdapter(n);try{return await t.open(e),F.info(`better-sqlite3 recovered after native module rebuild`),t}catch{}}}throw n}}let t=L.createNativeAdapter();return await t.open(e),t}case`sqljs`:{let t=L.createFallbackAdapter();return await t.open(e),t}default:{let e=t.kind;throw Error(`Unknown driver kind: ${e}`)}}}async function je(e){let t=new P;return await t.open(e),t}const L={BetterSqlite3Adapter:T,SqlJsAdapter:P,isVitestRuntime:ke,resolveAikitPackageRoot:x,resolveAikitRuntimeRoot:S,isNpxRuntimeRoot:le,readAikitPackageSpec:C,resolvePersistentNativeRuntimeRoot:de,ensureRuntimeRootPackageJson:w,resolveNativeModulePackageDir:E,resolveNativeBindingPath:me,resolveNativeModuleVersion:fe,probeNativeModuleAbi:he,tryRebuildNativeModule:ge,tryInstallNativeModule:_e,preparePreferredNativeRuntime:Ae,createNativeAdapter:e=>new T(e),createFallbackAdapter:()=>new P},R=new Set([`sessions`,`stash`,`checkpoints`,`leases`,`signals`,`audit_log`,`replay_entries`,`session_metadata`]);function Me(e){let t=te(e)||`.db`,n=ee(e,t);return h(m(e),`${n}-control${t}`)}function Ne(e){return R.has(e)?`control`:`content`}function z(e,t={}){let n=t.splitEnabled??!1;return{splitEnabled:n,contentDbPath:t.contentDbPath??e,controlDbPath:t.controlDbPath??(n?Me(e):e)}}function Pe(e,t=process.env){let n=t.AIKIT_SPLIT_STATE?.trim().toLowerCase();return z(e,{splitEnabled:n===`1`||n===`true`||n===`yes`||n===`on`})}const B=`_state_partition_meta`;function V(e){return`"${e.replaceAll(`"`,`""`)}"`}function Fe(e){let t=m(e);c(t)||l(t,{recursive:!0})}async function H(e){return Fe(e),I(e)}function U(e,t){return e.queryAll(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`,[t]).length>0}function Ie(e,t){return e.queryAll(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`,[t])[0]?.sql??void 0}function Le(e,t){return e.queryAll(`PRAGMA table_info(${V(t)})`).map(e=>e.name)}function W(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${V(t)}`)[0]?.count??0}function Re(e,t,n){if(!U(e,n))return;if(!U(t,n)){let r=Ie(e,n);if(!r)return;t.exec(r)}let r=Le(t,n);if(r.length===0)return;let i=r.map(V).join(`, `),a=r.map(()=>`?`).join(`, `),o=e.queryAll(`SELECT ${i} FROM ${V(n)}`);if(o.length===0)return;let s=`INSERT OR REPLACE INTO ${V(n)} (${i}) VALUES (${a})`;for(let e of o)t.run(s,r.map(t=>e[t]??null))}function ze(e){e.exec(`
|
|
115
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
114
|
+
FROM ${t.name}`,[a,r]);let s=e.queryAll(`SELECT COUNT(*) AS cnt FROM memory_embeddings`)[0]?.cnt??0;i+=s-o}i>0&&oe.info(`[migration v4] backfilled ${i} embeddings into memory_embeddings`)}}],v=a(`sqlite-adapter`),y=e(import.meta.url),b=`better-sqlite3`;function ce(e){return e.replace(/\\/g,`/`)}function x(){return y.resolve(`@vpxa/aikit/package.json`).replace(/[\\/]package\.json$/,``)}function S(){return x().replace(/[\\/]node_modules[\\/]@vpxa[\\/]aikit$/,``)}function le(e){return ce(e).includes(`/_npx/`)}function C(){try{return JSON.parse(u(h(x(),`package.json`),`utf8`)).optionalDependencies?.[b]??`latest`}catch{return`latest`}}function ue(e){return e.replace(/[^a-zA-Z0-9._-]+/g,`_`)}function de(){let e=`${ue(C())}-${process.platform}-${process.arch}-abi${process.versions.modules}`;return h(re(),`.aikit`,`cache`,`native-modules`,b,e)}function w(e){l(e,{recursive:!0});let t=h(e,`package.json`);c(t)||p(t,`${JSON.stringify({name:`aikit-native-runtime-cache`,private:!0},null,2)}\n`,`utf8`)}function fe(e){let t=D(e);if(!t)return null;try{return JSON.parse(u(h(t,`package.json`),`utf8`)).version??null}catch{return null}}function T(e,t){try{let n={packageName:b,packageSpec:C(),packageVersion:fe(e),platform:process.platform,arch:process.arch,nodeAbi:process.versions.modules,installedAt:new Date().toISOString(),source:t};p(h(e,`.aikit-native-module.json`),`${JSON.stringify(n,null,2)}\n`,`utf8`)}catch(e){v.debug(`Failed to write better-sqlite3 runtime marker`,o(e))}}var E=class{runtimeRoot;type=`better-sqlite3`;kind=`better-sqlite3`;vectorCapable=!1;get capabilities(){return{vectorCapable:this.vectorCapable,persistentFile:!0,concurrentReaders:!0}}db=null;stmtCache=new Map;dbPath=``;DatabaseCtor=null;recovering=!1;constructor(e){this.runtimeRoot=e}async open(t){let n;try{let t=y;this.runtimeRoot!=null&&(w(this.runtimeRoot),t=e(h(this.runtimeRoot,`package.json`))),n=t(b)}catch(e){throw Error(`better-sqlite3 native binding unavailable: ${e instanceof Error?e.message:String(e)}`)}this.db=new n(t),this.dbPath=t,this.DatabaseCtor=n,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`),this.runIntegrityCheck(t,n)||(this.db?.pragma(`journal_mode = WAL`),this.db?.pragma(`foreign_keys = ON`),this.db?.pragma(`synchronous = NORMAL`));try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0,v.debug(`sqlite-vec extension loaded`)}catch(e){this.vectorCapable=!1,v.warn(`sqlite-vec extension failed to load; vector search disabled`,o(e))}}exec(e){try{this.getDb().exec(e)}catch(t){if(this.isCorruptionError(t)){this.recover(),this.getDb().exec(e);return}throw t}}pragma(e){this.getDb().pragma(e)}queryAll(e,t=[]){try{let n=this.prepareCached(e);return t.length>0?n.all(...t):n.all()}catch(n){if(this.isCorruptionError(n))return this.recover(),this.queryAll(e,t);throw n}}run(e,t){try{let n=this.prepareCached(e);return t===void 0?n.run():Array.isArray(t)?t.length===0?n.run():n.run(...t):n.run(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.run(e,t);throw n}}get(e,t){try{let n=this.prepareCached(e);return t===void 0?n.get():Array.isArray(t)?t.length>0?n.get(...t):n.get():n.get(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.get(e,t);throw n}}all(e,t){try{let n=this.prepareCached(e);return t===void 0?n.all():Array.isArray(t)?t.length>0?n.all(...t):n.all():n.all(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.all(e,t);throw n}}transaction(e){return this.getDb().transaction(()=>e(this.createTransactionHandle()))()}createTransactionHandle(){return{exec:e=>this.exec(e),get:(e,t)=>this.get(e,t),all:(e,t)=>this.all(e,t),run:(e,t)=>this.run(e,t)}}flush(){}async close(){this.db&&=(this.stmtCache.clear(),this.db.close(),null)}runIntegrityCheck(e,t){try{let t=this.db?.pragma(`integrity_check`);if(t.length===1&&t[0]?.integrity_check===`ok`)return!0;let n=t.map(e=>e.integrity_check).slice(0,5).join(`; `);v.warn(`Database integrity check failed — recreating`,{dbPath:e,issues:n})}catch(t){v.warn(`Integrity check query failed — recreating database`,{dbPath:e,error:o(t)})}try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{f(e)}catch{}try{f(`${e}-wal`)}catch{}try{f(`${e}-shm`)}catch{}return this.db=new t(e),v.info(`Database recreated successfully — full reindex required`,{dbPath:e}),!1}isCorruptionError(e){if(this.recovering)return!1;let t=e instanceof Error?e.message:String(e);return/database disk image is malformed|file is not a database|database or disk is full/.test(t)}recover(){if(this.recovering)throw Error(`BetterSqlite3Adapter: recovery already in progress`);this.recovering=!0;try{v.warn(`Runtime corruption detected — recovering database`,{dbPath:this.dbPath});try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{f(this.dbPath)}catch{}try{f(`${this.dbPath}-wal`)}catch{}try{f(`${this.dbPath}-shm`)}catch{}if(!this.DatabaseCtor)throw Error(`DatabaseCtor is not initialized`);this.db=this.DatabaseCtor(this.dbPath),this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`);try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0}catch{this.vectorCapable=!1}v.info(`Database recovered — full reindex required`,{dbPath:this.dbPath})}finally{this.recovering=!1}}getDb(){if(!this.db)throw Error(`BetterSqlite3Adapter: database not opened`);return this.db}prepareCached(e){let t=this.stmtCache.get(e);if(t)return t;let n=this.getDb().prepare(e);return this.stmtCache.set(e,n),n}};function D(e){if(e){let t=h(e,`node_modules`,b);return c(h(t,`package.json`))?t:null}try{return y.resolve(`${b}/package.json`).replace(/[\\/]package\.json$/,``)}catch{return null}}function pe(e){let t=D(e);if(!t)return null;let n=h(t,`build`,`Release`,`better_sqlite3.node`);return c(n)?n:null}async function me(e){let t=D(e);if(!t)return`package-missing`;if(!c(h(t,`build`,`Release`,`better_sqlite3.node`)))return`binding-missing`;try{let{execFileSync:t}=await import(`node:child_process`),n=e??S();return e&&w(e),t(process.execPath,[`-e`,`require('${b}')`],{cwd:n,stdio:`pipe`,timeout:15e3,windowsHide:!0}),`ok`}catch(e){let t=e instanceof Error&&`stderr`in e?String(e.stderr):``;return/NODE_MODULE_VERSION/.test(t)?`abi-mismatch`:/Could not locate the bindings file|no native build was found/.test(t)?`binding-missing`:`error`}}async function he(e,t=!1){let n=D(e);if(!n)return v.info(`better-sqlite3 package is not installed — skipping native rebuild`),!1;try{let{execFileSync:r}=await import(`node:child_process`),i=e??n.replace(/[\\/]node_modules[\\/]better-sqlite3$/,``),a=process.platform===`win32`?`npm.cmd`:`npm`;if(e&&w(e),t){let e=h(n,`build`,`Release`,`better_sqlite3.node`);if(c(e))try{f(e),v.info(`Deleted stale native binding before rebuild`,{path:e})}catch(t){v.warn(`Cannot delete stale native binding — file may be locked by another process`,{path:e,error:t instanceof Error?t.message:String(t)})}}return v.info(`Attempting native module rebuild for better-sqlite3`,{cwd:i}),r(a,[`rebuild`,b],{cwd:i,stdio:`pipe`,timeout:6e4,windowsHide:!0}),v.info(`Native module rebuild completed successfully`),T(i,`rebuild`),!0}catch(e){return v.warn(`Native module rebuild failed — continuing with sql.js fallback`,o(e)),!1}}async function ge(e){try{let{execFileSync:t}=await import(`node:child_process`),n=e??S(),r=process.platform===`win32`?`npm.cmd`:`npm`,i=C();return w(n),v.info(`Attempting to install better-sqlite3 for native adapter recovery`,{cwd:n,packageSpec:i}),t(r,[`install`,`--no-save`,`--package-lock=false`,`--no-audit`,`--no-fund`,`--omit=dev`,`${b}@${i}`],{cwd:n,stdio:`pipe`,timeout:12e4,windowsHide:!0}),v.info(`better-sqlite3 install completed successfully`),T(n,`install`),!0}catch(e){return v.warn(`better-sqlite3 install failed — continuing with sql.js fallback`,o(e)),!1}}const O=a(`driver-selector`),k=e(import.meta.url);var _e=class extends Error{code=`STORAGE_INITIALIZATION_FAILED`;failures;constructor(e){let t=e.map(e=>`[${e.code}] ${e.driver}: ${e.message}`).join(`; `);super(`All SQLite drivers failed to initialise (${e.length}): ${t}`),this.name=`StorageInitializationError`,this.failures=e}};function ve(e){let[t,n]=(e??process.versions.node).split(`.`),r=Number.parseInt(t??`0`,10);return r>22||r===22&&Number.parseInt(n??`0`,10)>=13}function ye(e){if(typeof e!=`function`)return!1;let t=e.prototype;return typeof t?.enableLoadExtension==`function`&&typeof t.loadExtension==`function`}function A(e,t,n){return{available:!1,failure:{driver:e,code:t,message:n}}}function j(e){return{available:!0,capabilities:e}}function be(){try{try{let e=k(`sqlite-vec`);if(typeof e.getLoadablePath==`function`){let t=e.getLoadablePath();if(t&&c(t))return t}if(e.loadablePath&&c(e.loadablePath))return e.loadablePath}catch{}let e=m(k.resolve(`sqlite-vec/package.json`)),t={"win32-x64":`sqlite-vec-win32-x64.node`,"win32-arm64":`sqlite-vec-win32-arm64.node`,"darwin-x64":`sqlite-vec-darwin-x64.node`,"darwin-arm64":`sqlite-vec-darwin-arm64.node`,"linux-x64":`sqlite-vec-linux-x64.node`,"linux-arm64":`sqlite-vec-linux-arm64.node`}[`${process.platform}-${process.arch}`];if(t){let n=h(e,t);if(c(n))return n}let n=h(e,`sqlite-vec.node`);if(c(n))return n;let r=h(m(k.resolve(`sqlite-vec`)),`sqlite-vec.node`);return c(r)?r:null}catch{return null}}async function M(){if(!ve())return A(`node-sqlite`,`NODE_VERSION_UNSUPPORTED`,`Node.js ${process.versions.node} < 22.13 — node:sqlite extension loading unavailable`);let e;try{let t=await import(`node:sqlite`);if(!ye(t.DatabaseSync))return A(`node-sqlite`,`EXTENSION_LOADING_DISABLED`,`node:sqlite is available but DatabaseSync extension loading APIs are unavailable`);e=t.DatabaseSync}catch(e){return A(`node-sqlite`,`MODULE_NOT_AVAILABLE`,`node:sqlite not available: ${e instanceof Error?e.message:String(e)}`)}let t=new e(`:memory:`,{allowExtension:!0});try{try{t.enableLoadExtension(!0)}catch(e){return A(`node-sqlite`,`EXTENSION_LOADING_DISABLED`,`enableLoadExtension failed: ${e instanceof Error?e.message:String(e)}`)}let e=be();if(!e)return A(`node-sqlite`,`NATIVE_BINARY_UNAVAILABLE`,`Could not resolve sqlite-vec native binary path`);try{t.loadExtension(e)}catch(e){return A(`node-sqlite`,`SQLITE_VEC_LOAD_FAILED`,`sqlite-vec loadExtension failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=t.prepare(`SELECT vec_version() AS v`).get();if(!e||typeof e.v!=`string`)return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() returned empty result`);O.debug(`node-sqlite: sqlite-vec ${e.v}`)}catch(e){return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=new Uint8Array(new Float32Array([1,0,0]).buffer),n=t.prepare(`SELECT vec_distance_cosine(?, ?) AS d`).get(e,e);if(!n||typeof n.d!=`number`)return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: unexpected result ${JSON.stringify(n)}`);O.debug(`node-sqlite: vector smoke test passed`)}catch(e){return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: ${e instanceof Error?e.message:String(e)}`)}}finally{try{t.enableLoadExtension(!1)}catch{}t.close()}return O.debug(`node:sqlite driver ready (sqlite-vec enabled)`),j({vectorCapable:!0,persistentFile:!0,concurrentReaders:!0})}async function N(){let e;try{e=k(`better-sqlite3`)}catch(e){return A(`better-sqlite3`,`MODULE_NOT_AVAILABLE`,`better-sqlite3 not available: ${e instanceof Error?e.message:String(e)}`)}let t;try{t=new e(`:memory:`)}catch(e){return A(`better-sqlite3`,`DATABASE_OPEN_FAILED`,`Failed to open in-memory database: ${e instanceof Error?e.message:String(e)}`)}try{try{k(`sqlite-vec`).load(t)}catch(e){return A(`better-sqlite3`,`SQLITE_VEC_LOAD_FAILED`,`sqlite-vec load failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=t.prepare(`SELECT vec_version() AS v`).get();if(!e||typeof e.v!=`string`)return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() returned empty result`);O.debug(`better-sqlite3: sqlite-vec ${e.v}`)}catch(e){return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=new Uint8Array(new Float32Array([1,0,0]).buffer),n=t.prepare(`SELECT vec_distance_cosine(?, ?) AS d`).get([e,e]);if(!n||typeof n.d!=`number`)return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: unexpected result ${JSON.stringify(n)}`);O.debug(`better-sqlite3: vector smoke test passed`)}catch(e){return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: ${e instanceof Error?e.message:String(e)}`)}}finally{t.close()}return O.debug(`better-sqlite3 driver ready (sqlite-vec enabled)`),j({vectorCapable:!0,persistentFile:!0,concurrentReaders:!0})}async function xe(){let e;try{let t=await import(`sql.js`);e=t.default??t}catch(e){return A(`sqljs`,`MODULE_NOT_AVAILABLE`,`sql.js module not available: ${e instanceof Error?e.message:String(e)}`)}let t;try{let e=m(k.resolve(`sql.js/package.json`)),n=h(e,`dist`,`sql-wasm.wasm`);c(n)&&(t=t=>t.endsWith(`.wasm`)?n:h(e,`dist`,t))}catch{}let n;try{n=await e(t?{locateFile:t}:void 0)}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`wasm`)||t.includes(`WASM`)||t.includes(`WebAssembly`)?A(`sqljs`,`WASM_INITIALIZATION_FAILED`,`sql.js WASM initialisation failed: ${t}`):A(`sqljs`,`WASM_ASSET_NOT_FOUND`,`sql.js initialisation failed (WASM asset may be missing): ${t}`)}try{new n.Database().close()}catch(e){return A(`sqljs`,`DATABASE_OPEN_FAILED`,`sql.js in-memory database failed: ${e instanceof Error?e.message:String(e)}`)}return O.debug(`sql.js driver ready (vector search disabled)`),j({vectorCapable:!1,persistentFile:!0,concurrentReaders:!1})}async function P(e){let t=e.driver??`auto`;if(t!==`auto`)return Se(t);let n=[];{let e=await M();if(e.available)return{kind:`node-sqlite`,capabilities:e.capabilities,failures:[]};e.failure&&n.push(e.failure)}{let e=await N();if(e.available)return{kind:`better-sqlite3`,capabilities:e.capabilities,failures:n};e.failure&&n.push(e.failure)}{let e=await xe();if(e.available)return{kind:`sqljs`,capabilities:e.capabilities,failures:n};e.failure&&n.push(e.failure)}throw new _e(n)}async function Se(e){let{kind:t,capabilities:n,failures:r}=await Ce(e);if(!n)throw new _e(r);return{kind:t,capabilities:n,failures:r}}async function Ce(e){let t=e;switch(e){case`node-sqlite`:{let e=await M();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}case`better-sqlite3`:{let e=await N();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}case`sqljs`:{let e=await xe();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}default:throw Error(`Unreachable: unknown driver mode "${e}"`)}}const we=e(import.meta.url),Te=a(`sqljs-adapter`);function Ee(e){return we.resolve(`sql.js/dist/${e}`)}function De(e){return e.match(/^\s*(?:INSERT(?:\s+OR\s+\w+)?\s+INTO|UPDATE)\s+([A-Za-z_][A-Za-z0-9_]*)/i)?.[1]??null}var F=class{type=`sql.js`;kind=`sqljs`;vectorCapable=!1;capabilities={vectorCapable:!1,persistentFile:!0,concurrentReaders:!1};db=null;dbPath=``;dirty=!1;flushTimer=null;DEBOUNCE_MS=1e3;MAX_DB_SIZE_BYTES=500*1024*1024;inTransaction=!1;foreignKeysEnabled=!1;async open(e){this.dbPath=e;let t=(await import(`sql.js`)).default,n=await t({locateFile:e=>Ee(e)});if(c(e)){let t=u(e);this.db=new n.Database(t)}else this.db=new n.Database}exec(e){let t=e.trimStart().toUpperCase();this.getDb().run(e),t.startsWith(`BEGIN`)?this.inTransaction=!0:(t.startsWith(`COMMIT`)||t.startsWith(`ROLLBACK`))&&(this.inTransaction=!1),this.markDirty()}pragma(e){let t=e.trim().toLowerCase();t===`foreign_keys = on`||t===`foreign_keys=on`?this.foreignKeysEnabled=!0:(t===`foreign_keys = off`||t===`foreign_keys=off`)&&(this.foreignKeysEnabled=!1),this.getDb().exec(`PRAGMA ${e}`)}queryAll(e,t=[]){let n=this.getDb().prepare(e);try{t.length>0&&n.bind(t);let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}execWrite(e,t){let n=this.getDb();if(t===void 0){n.run(e);return}let r=n.prepare(e);try{r.bind(t),r.step()}finally{r.free()}}toBindParams(e){if(e!==void 0)return Array.isArray(e)&&e.length===0?void 0:e}run(e,t){let n=this.getDb(),r=e.trimStart().toUpperCase(),i=De(e),a=this.foreignKeysEnabled&&!this.inTransaction&&i!==null&&(r.startsWith(`INSERT`)||r.startsWith(`UPDATE`));a&&n.run(`SAVEPOINT fk_check`);try{if(this.execWrite(e,this.toBindParams(t)),a){if(n.exec(`PRAGMA foreign_key_check(${i})`).length>0)throw n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`),Error(`FOREIGN KEY constraint failed`);n.run(`RELEASE fk_check`)}}catch(e){if(a)try{n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`)}catch{}throw e}return this.markDirty(),this.getChangesResult(n)}getChangesResult(e){let t=e.exec(`SELECT changes() AS changes, last_insert_rowid() AS rowid`),n=t[0]?.values[0]?.[0]??0,r=t[0]?.values[0]?.[1];return{changes:Number(n),lastInsertRowid:r===void 0?void 0:Number(r)}}get(e,t){let n=this.getDb().prepare(e);try{return t!==void 0&&(Array.isArray(t)?t.length>0&&n.bind(t):n.bind(t)),n.step()?n.getAsObject():void 0}finally{n.free()}}all(e,t){let n=this.getDb().prepare(e);try{t!==void 0&&(Array.isArray(t)?t.length>0&&n.bind(t):n.bind(t));let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}transaction(e){this.exec(`BEGIN IMMEDIATE`);try{let t=e(this.createTransactionHandle());return this.exec(`COMMIT`),t}catch(e){throw this.exec(`ROLLBACK`),e}}createTransactionHandle(){return{exec:e=>this.exec(e),get:(e,t)=>this.get(e,t),all:(e,t)=>this.all(e,t),run:(e,t)=>this.run(e,t)}}markDirty(e=!1){this.dirty=!0,e?this.flushImmediate():this.scheduleFlush()}scheduleFlush(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush()},this.DEBOUNCE_MS),this.flushTimer&&typeof this.flushTimer==`object`&&`unref`in this.flushTimer&&this.flushTimer.unref()}flushImmediate(){this.flushTimer&&=(clearTimeout(this.flushTimer),null),this.flush()}notifyCriticalWrite(){this.flushImmediate()}flush(){if(!this.dirty||!this.db)return;let e=this.db.export();e.byteLength>this.MAX_DB_SIZE_BYTES&&Te.warn(`Database size ${e.byteLength} bytes exceeds guardrail ${this.MAX_DB_SIZE_BYTES} bytes`);let t=`${this.dbPath}.tmp`,n=m(this.dbPath);n&&!c(n)&&l(n,{recursive:!0}),p(t,Buffer.from(e));try{f(this.dbPath)}catch{}d(t,this.dbPath),this.dirty=!1}async close(){if(this.flushTimer&&=(clearTimeout(this.flushTimer),null),this.db){let e=this.db,t;if(this.dirty)try{this.flush()}catch(e){t=e;try{f(`${this.dbPath}.tmp`)}catch{}}try{e.close()}finally{this.db=null}if(t)throw t}}getDb(){if(!this.db)throw Error(`SqlJsAdapter: database not opened`);return this.db}};const I=a(`sqlite-adapter`);e(import.meta.url);function Oe(){return!!process.env.VITEST||process.argv.some(e=>e.includes(`vitest`))}async function ke(){let e=R.resolveAikitRuntimeRoot(),t=await R.probeNativeModuleAbi(e);if(t===`ok`)return e;if(R.isNpxRuntimeRoot(e)){let e=R.resolvePersistentNativeRuntimeRoot(),t=await R.probeNativeModuleAbi(e);if(t===`ok`)return I.info(`Using cached better-sqlite3 native runtime`,{runtimeRoot:e,version:R.resolveNativeModuleVersion(e)}),e;let n=!1;if(t===`abi-mismatch`?(I.info(`Persistent better-sqlite3 cache ABI mismatch — rebuilding cached binding`),n=await R.tryRebuildNativeModule(e,!0)):t===`binding-missing`?(I.info(`Persistent better-sqlite3 cache missing binding — rebuilding cache`),n=await R.tryRebuildNativeModule(e,!1)):(I.info(`Persistent better-sqlite3 cache missing — installing cached runtime`,{runtimeRoot:e,packageSpec:R.readAikitPackageSpec()}),n=await R.tryInstallNativeModule(e)),n&&await R.probeNativeModuleAbi(e)===`ok`)return I.info(`Persistent better-sqlite3 cache ready`,{runtimeRoot:e,version:R.resolveNativeModuleVersion(e)}),e}if(t===`abi-mismatch`){if(I.info(`Detected NODE_MODULE_VERSION mismatch via pre-flight probe — rebuilding before load`),await R.tryRebuildNativeModule(e,!0)&&await R.probeNativeModuleAbi(e)===`ok`)return I.info(`Pre-flight rebuild succeeded — proceeding with native adapter`),e}else if(t===`binding-missing`){if(I.info(`No native binding found — attempting rebuild before load`),await R.tryRebuildNativeModule(e,!1)&&await R.probeNativeModuleAbi(e)===`ok`)return e}else if(t===`package-missing`&&(I.info(`better-sqlite3 package is not installed — attempting install before load`),await R.tryInstallNativeModule(e)&&await R.probeNativeModuleAbi(e)===`ok`))return e;return null}async function L(e){let t=await P({driver:process.env.AI_KIT_SQLITE_DRIVER??`auto`,databasePath:e});I.debug(`Storage backend: ${t.kind}`);for(let e of t.failures)I.warn(` ${e.driver}: ${e.code} — ${e.message}`);switch(t.kind){case`node-sqlite`:{let{NodeSqliteAdapter:t}=await Promise.resolve().then(()=>mt),n=new t;return await n.open(e),n}case`better-sqlite3`:{if(!R.isVitestRuntime()){let t=await R.preparePreferredNativeRuntime(),n=R.createNativeAdapter(t??void 0);try{return await n.open(e),n}catch(n){let r=n instanceof Error?n.message:String(n);if(!R.isVitestRuntime()&&/NODE_MODULE_VERSION|Could not locate the bindings file|no native build was found/.test(r)){let n=t??R.resolveAikitRuntimeRoot();if(await R.tryRebuildNativeModule(n,!1)){let t=R.createNativeAdapter(n);try{return await t.open(e),I.info(`better-sqlite3 recovered after native module rebuild`),t}catch{}}}throw n}}let t=R.createNativeAdapter();return await t.open(e),t}case`sqljs`:{let t=R.createFallbackAdapter();return await t.open(e),t}default:{let e=t.kind;throw Error(`Unknown driver kind: ${e}`)}}}async function Ae(e){let t=new F;return await t.open(e),t}const R={BetterSqlite3Adapter:E,SqlJsAdapter:F,isVitestRuntime:Oe,resolveAikitPackageRoot:x,resolveAikitRuntimeRoot:S,isNpxRuntimeRoot:le,readAikitPackageSpec:C,resolvePersistentNativeRuntimeRoot:de,ensureRuntimeRootPackageJson:w,resolveNativeModulePackageDir:D,resolveNativeBindingPath:pe,resolveNativeModuleVersion:fe,probeNativeModuleAbi:me,tryRebuildNativeModule:he,tryInstallNativeModule:ge,preparePreferredNativeRuntime:ke,createNativeAdapter:e=>new E(e),createFallbackAdapter:()=>new F},z=new Set([`sessions`,`stash`,`checkpoints`,`leases`,`signals`,`audit_log`,`replay_entries`,`session_metadata`]);function je(e){let t=ne(e)||`.db`,n=te(e,t);return h(m(e),`${n}-control${t}`)}function Me(e){return z.has(e)?`control`:`content`}function B(e,t={}){let n=t.splitEnabled??!1;return{splitEnabled:n,contentDbPath:t.contentDbPath??e,controlDbPath:t.controlDbPath??(n?je(e):e)}}function Ne(e,t=process.env){let n=t.AIKIT_SPLIT_STATE?.trim().toLowerCase();return B(e,{splitEnabled:n===`1`||n===`true`||n===`yes`||n===`on`})}const V=`_state_partition_meta`;function H(e){return`"${e.replaceAll(`"`,`""`)}"`}function Pe(e){let t=m(e);c(t)||l(t,{recursive:!0})}async function U(e){return Pe(e),L(e)}function W(e,t){return e.queryAll(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`,[t]).length>0}function Fe(e,t){return e.queryAll(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`,[t])[0]?.sql??void 0}function Ie(e,t){return e.queryAll(`PRAGMA table_info(${H(t)})`).map(e=>e.name)}function Le(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${H(t)}`)[0]?.count??0}function Re(e,t,n){if(!W(e,n))return;if(!W(t,n)){let r=Fe(e,n);if(!r)return;t.exec(r)}let r=Ie(t,n);if(r.length===0)return;let i=r.map(H).join(`, `),a=r.map(()=>`?`).join(`, `),o=e.queryAll(`SELECT ${i} FROM ${H(n)}`);if(o.length===0)return;let s=`INSERT OR REPLACE INTO ${H(n)} (${i}) VALUES (${a})`;for(let e of o)t.run(s,r.map(t=>e[t]??null))}function ze(e){e.exec(`
|
|
115
|
+
CREATE TABLE IF NOT EXISTS ${V} (
|
|
116
116
|
key TEXT PRIMARY KEY,
|
|
117
117
|
value TEXT NOT NULL,
|
|
118
118
|
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
119
119
|
)
|
|
120
|
-
`)}function Be(e,t,n){ze(e),e.run(`INSERT INTO ${
|
|
120
|
+
`)}function Be(e,t,n){ze(e),e.run(`INSERT INTO ${V} (key, value, updated_at)
|
|
121
121
|
VALUES (?, ?, datetime('now'))
|
|
122
122
|
ON CONFLICT(key) DO UPDATE SET
|
|
123
123
|
value = excluded.value,
|
|
124
|
-
updated_at = datetime('now')`,[`split-state`,JSON.stringify({splitEnabled:t.splitEnabled,contentDbPath:t.contentDbPath,controlDbPath:t.controlDbPath,migratedTables:n})])}async function Ve(e){let t=e.contentDbPath??e.controlDbPath;if(!t)throw Error(`migrateToSplitState requires at least one database path in config`);let n=
|
|
124
|
+
updated_at = datetime('now')`,[`split-state`,JSON.stringify({splitEnabled:t.splitEnabled,contentDbPath:t.contentDbPath,controlDbPath:t.controlDbPath,migratedTables:n})])}async function Ve(e){let t=e.contentDbPath??e.controlDbPath;if(!t)throw Error(`migrateToSplitState requires at least one database path in config`);let n=B(t,e);if(!n.splitEnabled||n.controlDbPath===n.contentDbPath)return;let r=await U(n.contentDbPath),i=await U(n.controlDbPath);try{g(i,_);let e=[];for(let t of z){if(!W(r,t))continue;Re(r,i,t);let n=Le(r,t),a=Le(i,t);if(a<n)throw Error(`Split-state migration verification failed for ${t}: source=${n} target=${a}`);e.push(t)}Be(i,n,e)}finally{r.close(),i.close()}}var He=class{adapter=null;reopenPromise=null;dbPath;externalAdapter;constructor(e={}){if(e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let n=e.path??t.data;this.dbPath=h(n,`graph.db`),this.externalAdapter=!1}}async initialize(){if(this.externalAdapter){let e=this.getAdapter();this.createTables(e),this.migrateSchema(e),e.flush();return}let e=m(this.dbPath);c(e)||l(e,{recursive:!0}),this.adapter=await L(this.dbPath),this.configureAdapter(this.adapter),this.createTables(this.adapter),this.migrateSchema(this.adapter),this.adapter.flush()}configureAdapter(e){e.pragma(`journal_mode = WAL`),e.pragma(`foreign_keys = ON`)}createTables(e){e.exec(`
|
|
125
125
|
CREATE TABLE IF NOT EXISTS nodes (
|
|
126
126
|
id TEXT PRIMARY KEY,
|
|
127
127
|
type TEXT NOT NULL,
|
|
@@ -162,7 +162,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
162
162
|
FOREIGN KEY (process_id) REFERENCES processes(id) ON DELETE CASCADE,
|
|
163
163
|
FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
|
|
164
164
|
)
|
|
165
|
-
`),e.exec(`CREATE INDEX IF NOT EXISTS idx_process_steps_node ON process_steps(node_id)`)}migrateSchema(e){for(let t of[`ALTER TABLE edges ADD COLUMN confidence REAL DEFAULT 1.0`,`ALTER TABLE nodes ADD COLUMN community TEXT`])try{e.exec(t)}catch{}e.exec(`CREATE INDEX IF NOT EXISTS idx_nodes_community ON nodes(community)`)}getAdapter(){if(!this.adapter)throw Error(`SqliteGraphStore not initialized — call initialize() first`);return this.adapter}async ensureOpen(){if(this.adapter)return;if(this.externalAdapter)throw Error(`SqliteGraphStore: external adapter has been closed by its owner; cannot reopen`);if(this.reopenPromise)return this.reopenPromise;let e=this.reopenAdapter();this.reopenPromise=e;try{await e}finally{this.reopenPromise===e&&(this.reopenPromise=null)}}async reopenAdapter(){let e=await
|
|
165
|
+
`),e.exec(`CREATE INDEX IF NOT EXISTS idx_process_steps_node ON process_steps(node_id)`)}migrateSchema(e){for(let t of[`ALTER TABLE edges ADD COLUMN confidence REAL DEFAULT 1.0`,`ALTER TABLE nodes ADD COLUMN community TEXT`])try{e.exec(t)}catch{}e.exec(`CREATE INDEX IF NOT EXISTS idx_nodes_community ON nodes(community)`)}getAdapter(){if(!this.adapter)throw Error(`SqliteGraphStore not initialized — call initialize() first`);return this.adapter}async ensureOpen(){if(this.adapter)return;if(this.externalAdapter)throw Error(`SqliteGraphStore: external adapter has been closed by its owner; cannot reopen`);if(this.reopenPromise)return this.reopenPromise;let e=this.reopenAdapter();this.reopenPromise=e;try{await e}finally{this.reopenPromise===e&&(this.reopenPromise=null)}}async reopenAdapter(){let e=await L(this.dbPath);this.configureAdapter(e),this.adapter=e}query(e,t=[]){return this.getAdapter().queryAll(e,t)}run(e,t=[]){this.getAdapter().run(e,t)}async upsertNode(e){await this.ensureOpen(),this.run(`INSERT INTO nodes (id, type, name, properties, source_record_id, source_path, created_at, community)
|
|
166
166
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
167
167
|
ON CONFLICT(id) DO UPDATE SET
|
|
168
168
|
type = excluded.type, name = excluded.name, properties = excluded.properties,
|
|
@@ -171,12 +171,12 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
171
171
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
172
172
|
ON CONFLICT(id) DO UPDATE SET
|
|
173
173
|
from_id = excluded.from_id, to_id = excluded.to_id,
|
|
174
|
-
type = excluded.type, weight = excluded.weight, confidence = excluded.confidence, properties = excluded.properties`,[e.id,e.fromId,e.toId,e.type,e.weight??1,e.confidence??1,JSON.stringify(e.properties??{})]),this.getAdapter().flush()}async upsertNodes(e){if(e.length===0)return;await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN
|
|
174
|
+
type = excluded.type, weight = excluded.weight, confidence = excluded.confidence, properties = excluded.properties`,[e.id,e.fromId,e.toId,e.type,e.weight??1,e.confidence??1,JSON.stringify(e.properties??{})]),this.getAdapter().flush()}async upsertNodes(e){if(e.length===0)return;await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN IMMEDIATE`);try{for(let t of e)this.run(`INSERT INTO nodes (id, type, name, properties, source_record_id, source_path, created_at, community)
|
|
175
175
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
176
176
|
ON CONFLICT(id) DO UPDATE SET
|
|
177
177
|
type = excluded.type, name = excluded.name, properties = excluded.properties,
|
|
178
178
|
source_record_id = excluded.source_record_id, source_path = excluded.source_path,
|
|
179
|
-
community = excluded.community`,[t.id,t.type,t.name,JSON.stringify(t.properties),t.sourceRecordId??null,t.sourcePath??null,t.createdAt??new Date().toISOString(),t.community??null]);t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async upsertEdges(e){if(e.length===0)return;await this.ensureOpen();let t=this.getAdapter();t.pragma(`foreign_keys = OFF`),t.exec(`BEGIN
|
|
179
|
+
community = excluded.community`,[t.id,t.type,t.name,JSON.stringify(t.properties),t.sourceRecordId??null,t.sourcePath??null,t.createdAt??new Date().toISOString(),t.community??null]);t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async upsertEdges(e){if(e.length===0)return;await this.ensureOpen();let t=this.getAdapter();t.pragma(`foreign_keys = OFF`),t.exec(`BEGIN IMMEDIATE`);try{for(let t of e)this.run(`INSERT INTO edges (id, from_id, to_id, type, weight, confidence, properties)
|
|
180
180
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
181
181
|
ON CONFLICT(id) DO UPDATE SET
|
|
182
182
|
from_id = excluded.from_id, to_id = excluded.to_id,
|
|
@@ -192,7 +192,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
192
192
|
n.id AS node_id, n.type AS node_type, n.name AS node_name, n.properties AS node_props,
|
|
193
193
|
n.source_record_id AS node_src_rec, n.source_path AS node_src_path,
|
|
194
194
|
n.created_at AS node_created, n.community AS node_community
|
|
195
|
-
FROM edges e JOIN nodes n ON e.from_id = n.id WHERE e.to_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(Ge(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(Ke(e)))}return{nodes:a,edges:o}}async traverse(e,t){await this.ensureOpen();let n=t?.maxDepth??2,r=t?.direction??`both`,i=t?.edgeType,a=t?.limit??50,o=new Map,s=new Map,c=new Set,l=[{nodeId:e,depth:0}];for(;l.length>0&&o.size<a;){let e=l.shift();if(!e||c.has(e.nodeId)||e.depth>n)continue;c.add(e.nodeId);let t=await this.getNeighbors(e.nodeId,{direction:r,edgeType:i,limit:a-o.size});for(let r of t.nodes)o.has(r.id)||(o.set(r.id,r),e.depth+1<n&&l.push({nodeId:r.id,depth:e.depth+1}));for(let e of t.edges)s.set(e.id,e)}return{nodes:[...o.values()],edges:[...s.values()]}}async findNodes(e){await this.ensureOpen();let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.namePattern&&(t.push(`name LIKE ?`),n.push(`%${e.namePattern}%`)),e.sourcePath&&(t.push(`source_path = ?`),n.push(e.sourcePath));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM nodes ${r} LIMIT ?`,[...n,i]).map(e=>Ue(e))}async findEdges(e){await this.ensureOpen();let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.fromId&&(t.push(`from_id = ?`),n.push(e.fromId)),e.toId&&(t.push(`to_id = ?`),n.push(e.toId));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM edges ${r} LIMIT ?`,[...n,i]).map(e=>We(e))}async deleteNode(e){await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN
|
|
195
|
+
FROM edges e JOIN nodes n ON e.from_id = n.id WHERE e.to_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(Ge(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(Ke(e)))}return{nodes:a,edges:o}}async traverse(e,t){await this.ensureOpen();let n=t?.maxDepth??2,r=t?.direction??`both`,i=t?.edgeType,a=t?.limit??50,o=new Map,s=new Map,c=new Set,l=[{nodeId:e,depth:0}];for(;l.length>0&&o.size<a;){let e=l.shift();if(!e||c.has(e.nodeId)||e.depth>n)continue;c.add(e.nodeId);let t=await this.getNeighbors(e.nodeId,{direction:r,edgeType:i,limit:a-o.size});for(let r of t.nodes)o.has(r.id)||(o.set(r.id,r),e.depth+1<n&&l.push({nodeId:r.id,depth:e.depth+1}));for(let e of t.edges)s.set(e.id,e)}return{nodes:[...o.values()],edges:[...s.values()]}}async findNodes(e){await this.ensureOpen();let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.namePattern&&(t.push(`name LIKE ?`),n.push(`%${e.namePattern}%`)),e.sourcePath&&(t.push(`source_path = ?`),n.push(e.sourcePath));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM nodes ${r} LIMIT ?`,[...n,i]).map(e=>Ue(e))}async findEdges(e){await this.ensureOpen();let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.fromId&&(t.push(`from_id = ?`),n.push(e.fromId)),e.toId&&(t.push(`to_id = ?`),n.push(e.toId));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM edges ${r} LIMIT ?`,[...n,i]).map(e=>We(e))}async deleteNode(e){await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN IMMEDIATE`);try{this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e,e]),this.run(`DELETE FROM nodes WHERE id = ?`,[e]),t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async deleteBySourcePath(e){await this.ensureOpen();let t=this.query(`SELECT id FROM nodes WHERE source_path = ?`,[e]);if(t.length===0)return 0;let n=this.getAdapter();n.exec(`BEGIN IMMEDIATE`);try{for(let e of t)this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e.id,e.id]);this.run(`DELETE FROM nodes WHERE source_path = ?`,[e]),n.exec(`COMMIT`),n.flush()}catch(e){throw n.exec(`ROLLBACK`),e}return t.length}async clear(){await this.ensureOpen();let e=this.getAdapter();e.exec(`BEGIN IMMEDIATE`);try{this.run(`DELETE FROM process_steps`),this.run(`DELETE FROM processes`),this.run(`DELETE FROM edges`),this.run(`DELETE FROM nodes`),e.exec(`COMMIT`)}catch(t){throw e.exec(`ROLLBACK`),t}e.flush()}async getStats(){await this.ensureOpen();let e=this.query(`SELECT COUNT(*) as count FROM nodes`)[0]?.count??0,t=this.query(`SELECT COUNT(*) as count FROM edges`)[0]?.count??0,n=this.query(`SELECT type, COUNT(*) as count FROM nodes GROUP BY type`),r={};for(let e of n)r[e.type]=e.count;let i=this.query(`SELECT type, COUNT(*) as count FROM edges GROUP BY type`),a={};for(let e of i)a[e.type]=e.count;return{nodeCount:e,edgeCount:t,nodeTypes:r,edgeTypes:a}}async validate(){await this.ensureOpen();let e=await this.getStats(),t=this.query(`SELECT e.id AS edgeId,
|
|
196
196
|
CASE
|
|
197
197
|
WHEN n1.id IS NULL THEN e.from_id
|
|
198
198
|
WHEN n2.id IS NULL THEN e.to_id
|
|
@@ -206,11 +206,11 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
206
206
|
LEFT JOIN edges e2 ON n.id = e2.to_id
|
|
207
207
|
WHERE e1.id IS NULL AND e2.id IS NULL`).map(e=>e.id);return{valid:t.length===0,orphanNodes:n,danglingEdges:t,stats:e}}async setNodeCommunity(e,t){await this.ensureOpen(),this.run(`UPDATE nodes SET community = ? WHERE id = ?`,[t,e]),this.getAdapter().flush()}async detectCommunities(){await this.ensureOpen();let e=this.query(`SELECT id FROM nodes`),t=new Map;for(let n of e)t.set(n.id,n.id);for(let n=0;n<10;n++){let n=!1,r=new Map(t);for(let i of e){let e=this.query(`SELECT to_id AS neighbor_id FROM edges WHERE from_id = ?
|
|
208
208
|
UNION
|
|
209
|
-
SELECT from_id AS neighbor_id FROM edges WHERE to_id = ?`,[i.id,i.id]),a=new Map,o=t.get(i.id)??i.id;a.set(o,1);for(let n of e){let e=t.get(n.neighbor_id)??n.neighbor_id;a.set(e,(a.get(e)??0)+1)}let s=o,c=0;for(let[e,t]of a)(t>c||t===c&&e<s)&&(c=t,s=e);o!==s&&(r.set(i.id,s),n=!0)}t.clear();for(let[e,n]of r)t.set(e,n);if(!n)break}let n=this.getAdapter();n.exec(`BEGIN
|
|
209
|
+
SELECT from_id AS neighbor_id FROM edges WHERE to_id = ?`,[i.id,i.id]),a=new Map,o=t.get(i.id)??i.id;a.set(o,1);for(let n of e){let e=t.get(n.neighbor_id)??n.neighbor_id;a.set(e,(a.get(e)??0)+1)}let s=o,c=0;for(let[e,t]of a)(t>c||t===c&&e<s)&&(c=t,s=e);o!==s&&(r.set(i.id,s),n=!0)}t.clear();for(let[e,n]of r)t.set(e,n);if(!n)break}let n=this.getAdapter();n.exec(`BEGIN IMMEDIATE`);try{for(let[e,n]of t)this.run(`UPDATE nodes SET community = ? WHERE id = ?`,[n,e]);n.exec(`COMMIT`),n.flush()}catch(e){throw n.exec(`ROLLBACK`),e}let r={};for(let[e,n]of t)r[n]||(r[n]=[]),r[n].push(e);return r}async traceProcess(e,t){await this.ensureOpen();let n=[],r=new Set,i=[e];for(;i.length>0;){let e=i.shift();if(!e||r.has(e))continue;r.add(e),n.push(e);let t=this.query(`SELECT to_id FROM edges WHERE from_id = ? AND type = 'calls'`,[e]);for(let e of t)r.has(e.to_id)||i.push(e.to_id)}let a=`proc_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=new Date().toISOString(),s=this.getAdapter();s.exec(`BEGIN IMMEDIATE`);try{this.run(`INSERT INTO processes (id, entry_node_id, label, properties, created_at)
|
|
210
210
|
VALUES (?, ?, ?, '{}', ?)`,[a,e,t,o]);for(let e=0;e<n.length;e++)this.run(`INSERT INTO process_steps (process_id, node_id, step_order) VALUES (?, ?, ?)`,[a,n[e],e]);s.exec(`COMMIT`),s.flush()}catch(e){throw s.exec(`ROLLBACK`),e}return{id:a,entryNodeId:e,label:t,properties:{},steps:n,createdAt:o}}async getProcesses(e){await this.ensureOpen();let t;t=e?this.query(`SELECT DISTINCT p.id, p.entry_node_id, p.label, p.properties, p.created_at
|
|
211
211
|
FROM processes p
|
|
212
212
|
JOIN process_steps ps ON p.id = ps.process_id
|
|
213
|
-
WHERE ps.node_id = ?`,[e]):this.query(`SELECT * FROM processes`);let n=[];for(let e of t){let t=this.query(`SELECT node_id FROM process_steps WHERE process_id = ? ORDER BY step_order`,[e.id]);n.push({id:e.id,entryNodeId:e.entry_node_id,label:e.label,properties:G(e.properties),steps:t.map(e=>e.node_id),createdAt:e.created_at})}return n}async deleteProcess(e){await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN
|
|
213
|
+
WHERE ps.node_id = ?`,[e]):this.query(`SELECT * FROM processes`);let n=[];for(let e of t){let t=this.query(`SELECT node_id FROM process_steps WHERE process_id = ? ORDER BY step_order`,[e.id]);n.push({id:e.id,entryNodeId:e.entry_node_id,label:e.label,properties:G(e.properties),steps:t.map(e=>e.node_id),createdAt:e.created_at})}return n}async deleteProcess(e){await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN IMMEDIATE`);try{this.run(`DELETE FROM process_steps WHERE process_id = ?`,[e]),this.run(`DELETE FROM processes WHERE id = ?`,[e]),t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async depthGroupedTraversal(e,t=3,n){await this.ensureOpen();let r=n?.direction??`both`,i=n?.edgeType,a=n?.limit??100,o={},s=new Set;s.add(e);let c=[e];for(let e=1;e<=t;e++){let t=[],n=[];for(let e of c){let o=await this.getNeighbors(e,{direction:r,edgeType:i,limit:a});for(let e of o.nodes)s.has(e.id)||(s.add(e.id),t.push(e.id),n.push(e))}if(n.length>0&&(o[e]=n),c=t,c.length===0||s.size>=a)break}return o}async getCohesionScore(e){await this.ensureOpen();let t=this.query(`SELECT id FROM nodes WHERE community = ?`,[e]);if(t.length===0)return 0;let n=new Set(t.map(e=>e.id)),r=t.map(()=>`?`).join(`,`),i=t.map(e=>e.id),a=this.query(`SELECT from_id, to_id FROM edges WHERE from_id IN (${r}) OR to_id IN (${r})`,[...i,...i]);if(a.length===0)return 0;let o=0;for(let e of a)n.has(e.from_id)&&n.has(e.to_id)&&o++;return o/a.length}async getSymbol360(e){let t=await this.getNode(e);if(!t)throw Error(`Node '${e}' not found`);let n=await this.findEdges({toId:e}),r=await this.findEdges({fromId:e}),i=await this.getProcesses(e);return{node:t,incoming:n,outgoing:r,community:t.community??null,processes:i}}releaseMemory(){if(this.adapter)try{this.adapter.exec(`PRAGMA shrink_memory`),this.adapter.exec(`PRAGMA wal_checkpoint(TRUNCATE)`)}catch{}}async close(){this.adapter&&=(this.externalAdapter||this.adapter.close(),null)}};function G(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}function Ue(e){return{id:e.id,type:e.type,name:e.name,properties:G(e.properties),sourceRecordId:e.source_record_id??void 0,sourcePath:e.source_path??void 0,createdAt:e.created_at,community:e.community??void 0}}function We(e){return{id:e.id,fromId:e.from_id,toId:e.to_id,type:e.type,weight:e.weight??1,confidence:e.confidence??1,properties:G(e.properties)}}function Ge(e){return{id:e.edge_id,fromId:e.from_id,toId:e.to_id,type:e.edge_type,weight:e.weight??1,confidence:e.edge_confidence??1,properties:G(e.edge_props??`{}`)}}function Ke(e){return{id:e.node_id,type:e.node_type,name:e.node_name,properties:G(e.node_props??`{}`),sourceRecordId:e.node_src_rec??void 0,sourcePath:e.node_src_path??void 0,createdAt:e.node_created,community:e.node_community??void 0}}function K(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n]<0?-e[n]:e[n];r>t&&(t=r)}let n=new Int8Array(e.length);if(t===0)return Buffer.from(n.buffer,n.byteOffset,n.byteLength);let r=127/t;for(let t=0;t<e.length;t++){let i=Math.round(e[t]*r);n[t]=i<-127?-127:i>127?127:i}return Buffer.from(n.buffer,n.byteOffset,n.byteLength)}const q=a(`sqlite-vec-store`);function qe(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function J(e){return!e||e.length===0?[]:[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]}const Y=`knowledge_meta`,Je=`embedding_profile`,X=Object.freeze({additionalFilterMultiplier:4,baseOverfetchMultiplier:4,filteredOverfetchMultiplier:8,filteredRetryMultiplier:2,maxCandidateLimit:512,maxExpansionFactor:4,minFilteredCandidateLimit:16,tagFilterMultiplier:4});function Ye(e){return{model:e.model,nativeDim:e.nativeDim,dimensions:e.dimensions,queryPrefix:e.queryPrefix,pooling:e.pooling,normalize:e.normalize}}function Xe(e){return JSON.stringify(Ye(e))}function Ze(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Qe=class{adapter=null;externalAdapter;dbPath;embeddingDim;embeddingProfile;coarseDim;vecTableName;vecTableCoarseName;vectorEnabled=!1;ftsEnabled=!1;warnedVectorDisabled=!1;_drainState=`idle`;_priorityQueue=[];_normalQueue=[];_closeWaiter=null;_onCloseHooks=[];_closing=!1;constructor(e={}){let t=e.embeddingProfile?.dimensions??e.embeddingDim??n.dimensions;this.embeddingDim=t,this.embeddingProfile=Ye(e.embeddingProfile??{model:n.model,nativeDim:n.nativeDim,dimensions:t,queryPrefix:n.queryPrefix}),this.coarseDim=Math.min(128,this.embeddingDim);let r=e.profileName?`_${e.profileName}`:``;if(this.vecTableName=`vec_knowledge${r}`,this.vecTableCoarseName=`vec_knowledge${r}_coarse`,e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let t=B(e.path??`${i.path}/aikit.db`,e.partition);this.dbPath=t.contentDbPath,this.externalAdapter=!1}}async initialize(){if(!this.adapter){let e=m(this.dbPath);c(e)||l(e,{recursive:!0}),this.adapter=await L(this.dbPath)}this.configureConnectionPragmas(),this.vectorEnabled=this.adapter.vectorCapable,g(this.adapter,_),this.createKnowledgeTable(),this.createKnowledgeTagsTable(),this.createFtsTable(),this.vectorEnabled?(this.ensureVecTable(),this.backfillCanonicalEmbeddingsIfNeeded()):this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,q.warn(`SqliteVecStore: vector search disabled (sqlite-vec extension not loaded). Hybrid search will return FTS-only results.`))}configureConnectionPragmas(){let e=this.getAdapter();e.pragma(`journal_mode = WAL`),e.pragma(`busy_timeout = 5000`)}getDiagnostics(){let e=this.adapter,t=e?e.constructor.name:`unknown`,n=null,r=this.externalAdapter?``:this.dbPath;if(r)try{n=ee(r).size}catch{n=null}return{adapterType:t,vectorSearchEnabled:this.vectorEnabled,ftsEnabled:this.ftsEnabled,degradedMode:!this.vectorEnabled,dbPath:r,dbSizeBytes:n,embeddingDim:this.embeddingDim,vectorDtype:`int8`,embeddingModel:this.embeddingProfile.model,embeddingProfile:this.embeddingProfile}}createKnowledgeTable(){let e=this.getAdapter();e.exec(`
|
|
214
214
|
CREATE TABLE IF NOT EXISTS knowledge (
|
|
215
215
|
id TEXT PRIMARY KEY,
|
|
216
216
|
content TEXT NOT NULL,
|
|
@@ -242,13 +242,13 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
242
242
|
tokenize = 'unicode61 remove_diacritics 2'
|
|
243
243
|
)
|
|
244
244
|
`),this.ftsEnabled=!0}catch(e){this.ftsEnabled=!1,q.warn(`FTS5 unavailable — keyword search disabled`,o(e))}}createEmbeddingProfileTable(){this.getAdapter().exec(`
|
|
245
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
245
|
+
CREATE TABLE IF NOT EXISTS ${Y} (
|
|
246
246
|
key TEXT PRIMARY KEY,
|
|
247
247
|
value TEXT NOT NULL
|
|
248
248
|
)
|
|
249
|
-
`)}getStoredEmbeddingProfile(){return this.getAdapter().queryAll(`SELECT value FROM ${
|
|
249
|
+
`)}getStoredEmbeddingProfile(){return this.getAdapter().queryAll(`SELECT value FROM ${Y} WHERE key = ? LIMIT 1`,[Je])[0]?.value??null}saveEmbeddingProfile(){this.getAdapter().run(`INSERT INTO ${Y} (key, value)
|
|
250
250
|
VALUES (?, ?)
|
|
251
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,[
|
|
251
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,[Je,Xe(this.embeddingProfile)])}dropVectorTables(){let e=this.getAdapter();for(let t of[this.vecTableName,this.vecTableCoarseName]){let n=e.queryAll(`SELECT name FROM sqlite_master WHERE type='table' AND (name = '${t}' OR name LIKE '${t}_%')`);for(let t of n)e.exec(`DROP TABLE IF EXISTS "${t.name}"`)}}ensureVecTable(){let e=this.getAdapter();this.createEmbeddingProfileTable();let t=Xe(this.embeddingProfile),n=this.getStoredEmbeddingProfile(),r=!1;n!==null&&n!==t&&(r=!0,q.warn(`Vec profile mismatch — dropping vector tables for recreation`,{storedProfile:n,activeProfile:t}));let i=e.queryAll(`SELECT name, sql FROM sqlite_master WHERE type='table' AND name='${this.vecTableName}'`);if(!r&&i.length>0){let e=i[0].sql??``,t=e.match(/(?:float|int8)\[(\d+)\]/i),n=t?Number(t[1]):null,a=/int8\[/i.test(e);(n!==null&&n!==this.embeddingDim||!a)&&(r=!0,q.warn(`Vec table schema mismatch — dropping for recreation`,{existingDim:n,newDim:this.embeddingDim,wasInt8:a}))}r&&this.dropVectorTables(),e.exec(`
|
|
252
252
|
CREATE VIRTUAL TABLE IF NOT EXISTS ${this.vecTableName} USING vec0(
|
|
253
253
|
embedding int8[${this.embeddingDim}] distance_metric=cosine,
|
|
254
254
|
+knowledge_id TEXT
|
|
@@ -265,7 +265,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
265
265
|
VALUES ('${this.vecTableName}', 0, ?, ?, ?, ?, 0, ?)
|
|
266
266
|
ON CONFLICT(index_name) DO UPDATE SET
|
|
267
267
|
canonical_count = excluded.canonical_count,
|
|
268
|
-
generation = excluded.generation`,[t,i,this.embeddingDim,r,n])}catch(e){q.warn(`backfillCanonicalEmbeddings: failed to update vector_index_metadata`,{error:o(e)})}}}enqueueWrite(e,t=!1){return new Promise((n,r)=>{let i=async()=>{try{n(await e())}catch(e){r(e)}};t?this._priorityQueue.push(i):this._normalQueue.push(i),this._drain()})}async _drain(){if(
|
|
268
|
+
generation = excluded.generation`,[t,i,this.embeddingDim,r,n])}catch(e){q.warn(`backfillCanonicalEmbeddings: failed to update vector_index_metadata`,{error:o(e)})}}}enqueueWrite(e,t=!1){if(this._closing)throw Error(`SqliteVecStore: cannot enqueue write — store is closing`);return new Promise((n,r)=>{let i=async()=>{try{n(await e())}catch(e){r(e)}};t?this._priorityQueue.push(i):this._normalQueue.push(i),this._drainState===`idle`&&(this._drainState=`scheduled`,queueMicrotask(()=>this._drain()))})}async _drain(){if(this._drainState!==`draining`){this._drainState=`draining`;try{for(;this._priorityQueue.length>0||this._normalQueue.length>0;){let e=this._priorityQueue.shift()??this._normalQueue.shift();e&&await e()}}finally{if(this._drainState=`idle`,this._closeWaiter){let e=this._closeWaiter;this._closeWaiter=null,e.resolve(!1)}}}}async upsert(e,t){if(e.length!==0){if(e.length!==t.length)throw Error(`Record count (${e.length}) does not match vector count (${t.length})`);for(let n=0;n<t.length;n++)if(t[n].length===0)throw Error(`Zero-length vector at index ${n} for record ${e[n].sourcePath}`);return this.enqueueWrite(()=>this._upsertImpl(e,t))}}async upsertInteractive(e,t){if(e.length!==0){if(e.length!==t.length)throw Error(`Record count (${e.length}) does not match vector count (${t.length})`);for(let n=0;n<t.length;n++)if(t[n].length===0)throw Error(`Zero-length vector at index ${n} for record ${e[n].sourcePath}`);return this.enqueueWrite(()=>this._upsertImpl(e,t),!0)}}async upsertWithoutVector(e,t){return this.enqueueWrite(async()=>{let n=this.getAdapter(),r;if(this.vectorEnabled){let i=n.queryAll(`SELECT embedding FROM ${this.vecTableName} WHERE knowledge_id = ?`,[t]);if(i.length===0)throw Error(`upsertWithoutVector: source vector not found for ${t} — cannot create record ${e.id} without embedding. Call upsert() to re-embed.`);r=i[0].embedding}n.exec(`BEGIN IMMEDIATE`);let i=e;try{if(this.upsertKnowledgeRow(i),this.ftsEnabled&&(n.run(`DELETE FROM knowledge_fts WHERE id = ?`,[i.id]),n.run(`INSERT INTO knowledge_fts (id, content) VALUES (?, ?)`,[i.id,i.content])),this.vectorEnabled&&r&&(n.run(`DELETE FROM ${this.vecTableName} WHERE knowledge_id = ?`,[i.id]),n.run(`INSERT INTO ${this.vecTableName} (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[r,i.id]),this.coarseDim<this.embeddingDim)){let e=n.queryAll(`SELECT embedding FROM ${this.vecTableCoarseName} WHERE knowledge_id = ?`,[t]);e.length>0&&(n.run(`DELETE FROM ${this.vecTableCoarseName} WHERE knowledge_id = ?`,[i.id]),n.run(`INSERT INTO ${this.vecTableCoarseName} (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[e[0].embedding,i.id]))}n.exec(`COMMIT`)}catch(e){try{n.exec(`ROLLBACK`)}catch{}throw e}n.flush()})}upsertKnowledgeRow(e){this.getAdapter().run(`INSERT INTO knowledge (id, content, sourcePath, contentType, headingPath, chunkIndex,
|
|
269
269
|
totalChunks, startLine, endLine, fileHash, content_hash, indexedAt, origin, tags, category, version)
|
|
270
270
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
271
271
|
ON CONFLICT(id) DO UPDATE SET
|
|
@@ -283,7 +283,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
283
283
|
origin = excluded.origin,
|
|
284
284
|
tags = excluded.tags,
|
|
285
285
|
category = excluded.category,
|
|
286
|
-
version = excluded.version`,[e.id,e.content,e.sourcePath,e.contentType,e.headingPath??``,e.chunkIndex,e.totalChunks,e.startLine,e.endLine,e.fileHash,e.contentHash??``,e.indexedAt,e.origin,JSON.stringify(
|
|
286
|
+
version = excluded.version`,[e.id,e.content,e.sourcePath,e.contentType,e.headingPath??``,e.chunkIndex,e.totalChunks,e.startLine,e.endLine,e.fileHash,e.contentHash??``,e.indexedAt,e.origin,JSON.stringify(J(e.tags)),e.category??``,e.version])}replaceKnowledgeTags(e,t){let n=this.getAdapter(),r=J(t);if(n.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),r.length===0)return;let i=r.map(()=>`(?, ?)`).join(`, `),a=[];for(let t of r)a.push(e,t);n.run(`INSERT INTO knowledge_tags (knowledge_id, tag) VALUES ${i}`,a)}async _upsertImpl(e,t){let n=this.getAdapter();n.transaction(()=>{for(let r=0;r<e.length;r++){let i=e[r];if(this.upsertKnowledgeRow(i),this.replaceKnowledgeTags(i.id,i.tags),this.ftsEnabled&&(n.run(`DELETE FROM knowledge_fts WHERE id = ?`,[i.id]),n.run(`INSERT INTO knowledge_fts (id, content) VALUES (?, ?)`,[i.id,i.content])),this.vectorEnabled){if(n.run(`DELETE FROM ${this.vecTableName} WHERE knowledge_id = ?`,[i.id]),n.run(`INSERT INTO ${this.vecTableName} (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[K(t[r]),i.id]),this.coarseDim<this.embeddingDim){let e=t[r].subarray(0,this.coarseDim);n.run(`DELETE FROM ${this.vecTableCoarseName} WHERE knowledge_id = ?`,[i.id]),n.run(`INSERT INTO ${this.vecTableCoarseName} (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[K(e),i.id])}let e=Ze(t[r]);n.run(`INSERT OR REPLACE INTO memory_embeddings
|
|
287
287
|
(memory_id, embedding_model, embedding_version, dimensions, element_type, embedding, created_at)
|
|
288
288
|
VALUES (?, ?, ?, ?, ?, ?, ?)`,[i.id,this.embeddingProfile?.model??`default`,this.embeddingProfile?.version??`1`,t[r].length,`float32`,e,Date.now()])}}}),n.flush()}async search(e,t){if(e.length===0)return[];if(!this.vectorEnabled)return this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,q.warn(`search() called but vector backend is disabled — returning []`)),[];let n=t?.limit??r.maxResults,i=t?.minScore??r.minScore,a;try{a=this.runAdaptiveVectorSearch(this.vecTableName,K(e),t)}catch(e){return q.warn(`vector search failed`,o(e)),[]}return this.rowsToSearchResults(a,i,n)}async coarseSearch(e,t){if(!this.vectorEnabled||this.coarseDim>=this.embeddingDim)return this.search(e,t);let n=t?.limit??r.maxResults,i=t?.minScore??r.minScore,a=e.subarray(0,this.coarseDim),s;try{s=this.runAdaptiveVectorSearch(this.vecTableCoarseName,K(a),t)}catch(n){return q.warn(`coarse vector search failed, falling back to full search`,o(n)),this.search(e,t)}return s.length===0?this.search(e,t):this.rowsToSearchResults(s,i,n)}async ftsSearch(e,t){if(!e||e.trim().length===0||!this.ftsEnabled)return[];let n=this.getAdapter(),i=t?.limit??r.maxResults,a=this.buildFilterSqlSuffix(t,!0),s=`
|
|
289
289
|
SELECT k.*, bm25(knowledge_fts) AS _bm25
|
|
@@ -293,7 +293,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
293
293
|
${a.sql}
|
|
294
294
|
ORDER BY _bm25 ASC
|
|
295
295
|
LIMIT ?
|
|
296
|
-
`,c;try{let t=$e(e);c=n.queryAll(s,[t,...a.params,i])}catch(e){return q.warn(`fts search failed`,o(e)),[]}return c.map(e=>({record:this.fromRow(e),score:et(e._bm25)}))}async getById(e){let t=this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE id = ? LIMIT 1`,[e]);return t.length===0?null:this.fromRow(t[0])}async deleteBySourcePath(e){return this.enqueueWrite(()=>this._deleteBySourcePathImpl(e))}async _deleteBySourcePathImpl(e){let t=this.getAdapter(),n=t.queryAll(`SELECT id FROM knowledge WHERE sourcePath = ?`,[e]);if(n.length===0)return 0;t.exec(`BEGIN`);try{for(let{id:e}of n)this.vectorEnabled&&(t.run(`DELETE FROM ${this.vecTableName} WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM ${this.vecTableCoarseName} WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM memory_embeddings WHERE memory_id = ?`,[e]),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]);t.run(`DELETE FROM knowledge WHERE sourcePath = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw e}return t.flush(),n.length}async deleteById(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e))}async deleteByIdInteractive(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e),!0)}async _deleteByIdImpl(e){let t=this.getAdapter();if(t.queryAll(`SELECT id FROM knowledge WHERE id = ? LIMIT 1`,[e]).length===0)return!1;t.exec(`BEGIN`);try{this.vectorEnabled&&(t.run(`DELETE FROM ${this.vecTableName} WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM ${this.vecTableCoarseName} WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM memory_embeddings WHERE memory_id = ?`,[e]),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]),t.run(`DELETE FROM knowledge WHERE id = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw e}return t.flush(),!0}async getBySourcePath(e){return this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE sourcePath = ? ORDER BY chunkIndex ASC`,[e]).map(e=>this.fromRow(e))}async getStats(){let e=this.getAdapter(),t=e.queryAll(`SELECT COUNT(*) AS n FROM knowledge`)[0]?.n??0;if(t===0)return{totalRecords:0,totalFiles:0,contentTypeBreakdown:{},lastIndexedAt:null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model};let n=e.queryAll(`SELECT COUNT(DISTINCT sourcePath) AS n FROM knowledge`),r=e.queryAll(`SELECT contentType, COUNT(*) AS n FROM knowledge GROUP BY contentType`),i=e.queryAll(`SELECT MAX(indexedAt) AS ts FROM knowledge`),a={};for(let e of r)a[e.contentType]=e.n;return{totalRecords:t,totalFiles:n[0]?.n??0,contentTypeBreakdown:a,lastIndexedAt:i[0]?.ts??null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model}}async listSourcePaths(){return this.getAdapter().queryAll(`SELECT DISTINCT sourcePath FROM knowledge ORDER BY sourcePath`).map(e=>e.sourcePath)}async createFtsIndex(){this.createFtsTable()}async dropTable(){return this.enqueueWrite(()=>this._dropTableImpl())}async _dropTableImpl(){let e=this.getAdapter();this.ftsEnabled&&e.exec(`DROP TABLE IF EXISTS knowledge_fts`),this.vectorEnabled&&this.dropVectorTables(),e.exec(`DROP TABLE IF EXISTS ${
|
|
296
|
+
`,c;try{let t=$e(e);c=n.queryAll(s,[t,...a.params,i])}catch(e){return q.warn(`fts search failed`,o(e)),[]}return c.map(e=>({record:this.fromRow(e),score:et(e._bm25)}))}async getById(e){let t=this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE id = ? LIMIT 1`,[e]);return t.length===0?null:this.fromRow(t[0])}async deleteBySourcePath(e){return this.enqueueWrite(()=>this._deleteBySourcePathImpl(e))}async _deleteBySourcePathImpl(e){let t=this.getAdapter(),n=t.queryAll(`SELECT id FROM knowledge WHERE sourcePath = ?`,[e]);if(n.length===0)return 0;t.exec(`BEGIN IMMEDIATE`);try{for(let{id:e}of n)this.vectorEnabled&&(t.run(`DELETE FROM ${this.vecTableName} WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM ${this.vecTableCoarseName} WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM memory_embeddings WHERE memory_id = ?`,[e]),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]);t.run(`DELETE FROM knowledge WHERE sourcePath = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw t.flush(),e}return t.flush(),n.length}async deleteById(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e))}async deleteByIdInteractive(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e),!0)}async _deleteByIdImpl(e){let t=this.getAdapter();if(t.queryAll(`SELECT id FROM knowledge WHERE id = ? LIMIT 1`,[e]).length===0)return!1;t.exec(`BEGIN IMMEDIATE`);try{this.vectorEnabled&&(t.run(`DELETE FROM ${this.vecTableName} WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM ${this.vecTableCoarseName} WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM memory_embeddings WHERE memory_id = ?`,[e]),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]),t.run(`DELETE FROM knowledge WHERE id = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw t.flush(),e}return t.flush(),!0}async getBySourcePath(e){return this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE sourcePath = ? ORDER BY chunkIndex ASC`,[e]).map(e=>this.fromRow(e))}async getStats(){let e=this.getAdapter(),t=e.queryAll(`SELECT COUNT(*) AS n FROM knowledge`)[0]?.n??0;if(t===0)return{totalRecords:0,totalFiles:0,contentTypeBreakdown:{},lastIndexedAt:null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model};let n=e.queryAll(`SELECT COUNT(DISTINCT sourcePath) AS n FROM knowledge`),r=e.queryAll(`SELECT contentType, COUNT(*) AS n FROM knowledge GROUP BY contentType`),i=e.queryAll(`SELECT MAX(indexedAt) AS ts FROM knowledge`),a={};for(let e of r)a[e.contentType]=e.n;return{totalRecords:t,totalFiles:n[0]?.n??0,contentTypeBreakdown:a,lastIndexedAt:i[0]?.ts??null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model}}async listSourcePaths(){return this.getAdapter().queryAll(`SELECT DISTINCT sourcePath FROM knowledge ORDER BY sourcePath`).map(e=>e.sourcePath)}async createFtsIndex(){this.createFtsTable()}async dropTable(){return this.enqueueWrite(()=>this._dropTableImpl())}async _dropTableImpl(){let e=this.getAdapter();this.ftsEnabled&&e.exec(`DROP TABLE IF EXISTS knowledge_fts`),this.vectorEnabled&&this.dropVectorTables(),e.exec(`DROP TABLE IF EXISTS ${Y}`),e.exec(`DROP TABLE IF EXISTS knowledge_tags`),e.exec(`DROP TABLE IF EXISTS knowledge`),e.flush(),this.createKnowledgeTable(),this.createKnowledgeTagsTable(),this.createFtsTable(),this.vectorEnabled&&this.ensureVecTable()}releaseMemory(){if(this.adapter)try{this.adapter.exec(`PRAGMA shrink_memory`),this.adapter.exec(`PRAGMA wal_checkpoint(TRUNCATE)`)}catch{}}onBeforeClose(e){this._onCloseHooks.push(e)}async close(e=5e3){this._closing=!0;for(let e of this._onCloseHooks)try{e()}catch{}this._onCloseHooks.length=0,(this._priorityQueue.length>0||this._normalQueue.length>0||this._drainState!==`idle`)&&await new Promise(t=>{this._closeWaiter={resolve:t};let n=setTimeout(()=>{q.warn(`SqliteVecStore.close() timed out waiting for queue drain — force closing`),this._closeWaiter=null,t(!0)},e);n.unref&&n.unref(),this._drainState===`idle`&&(this._drainState=`scheduled`,queueMicrotask(()=>this._drain()))})&&(this._priorityQueue.length=0,this._normalQueue.length=0),this.adapter&&!this.externalAdapter&&this.adapter.close(),this.adapter=null}getAdapter(){if(!this.adapter)throw Error(`SqliteVecStore: not initialized — call initialize() first`);return this.adapter}runAdaptiveVectorSearch(e,t,n){let i=n?.limit??r.maxResults;if(i<=0)return[];let a=this.buildFilterSqlSuffix(n),o=this.buildVectorSearchPlan(i,a.profile),s=o.initialCandidateLimit,c=this.queryVectorRows(e,t,a,s,i);for(;o.hasFilters&&c.length<i&&s<o.maxCandidateLimit;)s=Math.min(o.maxCandidateLimit,Math.max(s+i,s*X.filteredRetryMultiplier)),c=this.queryVectorRows(e,t,a,s,i);return c}queryVectorRows(e,t,n,r,i){let a=this.getAdapter(),o=`
|
|
297
297
|
SELECT k.*, v.distance AS _distance
|
|
298
298
|
FROM (
|
|
299
299
|
SELECT knowledge_id, distance
|
|
@@ -306,7 +306,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
306
306
|
${n.sql}
|
|
307
307
|
ORDER BY v.distance ASC
|
|
308
308
|
LIMIT ?
|
|
309
|
-
`;return a.queryAll(o,[t,r,...n.params,i])}buildVectorSearchPlan(e,t){let n=Math.max(1,e*X.baseOverfetchMultiplier);if(!t.hasFilters)return{hasFilters:!1,initialCandidateLimit:n,maxCandidateLimit:n};let r=Math.max(0,t.filterCount-1),i=X.filteredOverfetchMultiplier+r*X.additionalFilterMultiplier+(t.tagCount>0?X.tagFilterMultiplier:0),a=Math.min(X.maxCandidateLimit,Math.max(e*i,X.minFilteredCandidateLimit));return{hasFilters:!0,initialCandidateLimit:a,maxCandidateLimit:Math.min(X.maxCandidateLimit,Math.max(a*X.maxExpansionFactor,e*X.filteredOverfetchMultiplier))}}rowsToSearchResults(e,t,n){return e.map(e=>({record:this.fromRow(e),score:1-(e._distance??1)})).filter(e=>e.score>=t).slice(0,n)}buildFilterSqlSuffix(e,t=!1){if(!e)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let n=[],r=[],i=0,a=0;if(e.contentType&&(n.push(`k.contentType = ?`),r.push(e.contentType),i++),e.sourceType){let t=s(e.sourceType);t.length>0&&(n.push(`k.contentType IN (${t.map(()=>`?`).join(`, `)})`),r.push(...t),i++)}if(e.origin&&(n.push(`k.origin = ?`),r.push(e.origin),i++),e.category&&(n.push(`k.category = ?`),r.push(e.category),i++),e.tags&&e.tags.length>0){let t=e.tags.map(()=>`?`).join(`, `);n.push(`EXISTS (SELECT 1 FROM knowledge_tags kt WHERE kt.knowledge_id = k.id AND kt.tag IN (${t}))`),r.push(...e.tags),i++,a=e.tags.length}if(n.length===0)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let o=n.join(` AND `);return{sql:t?`AND ${o}`:`WHERE ${o}`,params:r,profile:{filterCount:i,hasFilters:!0,tagCount:a}}}fromRow(e){return{id:e.id,content:e.content,sourcePath:e.sourcePath,contentType:e.contentType,headingPath:e.headingPath||void 0,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,startLine:e.startLine,endLine:e.endLine,fileHash:e.fileHash,contentHash:e.content_hash||void 0,indexedAt:e.indexedAt,origin:e.origin,tags:qe(e.tags),category:e.category||void 0,version:e.version}}};function $e(e){let t=e.replace(/["
|
|
309
|
+
`;return a.queryAll(o,[t,r,...n.params,i])}buildVectorSearchPlan(e,t){let n=Math.max(1,e*X.baseOverfetchMultiplier);if(!t.hasFilters)return{hasFilters:!1,initialCandidateLimit:n,maxCandidateLimit:n};let r=Math.max(0,t.filterCount-1),i=X.filteredOverfetchMultiplier+r*X.additionalFilterMultiplier+(t.tagCount>0?X.tagFilterMultiplier:0),a=Math.min(X.maxCandidateLimit,Math.max(e*i,X.minFilteredCandidateLimit));return{hasFilters:!0,initialCandidateLimit:a,maxCandidateLimit:Math.min(X.maxCandidateLimit,Math.max(a*X.maxExpansionFactor,e*X.filteredOverfetchMultiplier))}}rowsToSearchResults(e,t,n){return e.map(e=>({record:this.fromRow(e),score:1-(e._distance??1)})).filter(e=>e.score>=t).slice(0,n)}buildFilterSqlSuffix(e,t=!1){if(!e)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let n=[],r=[],i=0,a=0;if(e.contentType&&(n.push(`k.contentType = ?`),r.push(e.contentType),i++),e.sourceType){let t=s(e.sourceType);t.length>0&&(n.push(`k.contentType IN (${t.map(()=>`?`).join(`, `)})`),r.push(...t),i++)}if(e.origin&&(n.push(`k.origin = ?`),r.push(e.origin),i++),e.category&&(n.push(`k.category = ?`),r.push(e.category),i++),e.tags&&e.tags.length>0){let t=e.tags.map(()=>`?`).join(`, `);n.push(`EXISTS (SELECT 1 FROM knowledge_tags kt WHERE kt.knowledge_id = k.id AND kt.tag IN (${t}))`),r.push(...e.tags),i++,a=e.tags.length}if(n.length===0)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let o=n.join(` AND `);return{sql:t?`AND ${o}`:`WHERE ${o}`,params:r,profile:{filterCount:i,hasFilters:!0,tagCount:a}}}fromRow(e){return{id:e.id,content:e.content,sourcePath:e.sourcePath,contentType:e.contentType,headingPath:e.headingPath||void 0,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,startLine:e.startLine,endLine:e.endLine,fileHash:e.fileHash,contentHash:e.content_hash||void 0,indexedAt:e.indexedAt,origin:e.origin,tags:qe(e.tags),category:e.category||void 0,version:e.version}}};function $e(e){let t=[],n=e.replace(/"([^"]+)"/g,(e,n)=>(t.push(n),``)).replace(/[()*:^-]/g,` `).trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/["\\]/g,``)}"`),r=[...t.map(e=>`"${e}"`),...n];return r.length===0?`""`:r.join(` OR `)}function et(e){return e==null||Number.isNaN(e)?0:1-Math.exp(-Math.abs(e)/5)}function Z(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`,n=new Date(t);return Number.isNaN(n.getTime())?t:n.toISOString()}function Q(e){return`queryAll`in e&&`run`in e}function tt(e){return{get(t){return e.queryAll(`SELECT key, value, updated_at AS updatedAt FROM stash WHERE key = ?`,[t])[0]},set(t,n){e.run(`INSERT INTO stash (key, value)
|
|
310
310
|
VALUES (?, ?)
|
|
311
311
|
ON CONFLICT(key) DO UPDATE SET
|
|
312
312
|
value = excluded.value,
|
|
@@ -604,7 +604,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
604
604
|
ORDER BY retention_score ASC,
|
|
605
605
|
COALESCE(last_accessed_at, created_at) ASC,
|
|
606
606
|
entry_id ASC
|
|
607
|
-
LIMIT ?`),
|
|
607
|
+
LIMIT ?`),ee=e.prepare(`SELECT entry_id AS entryId,
|
|
608
608
|
tier,
|
|
609
609
|
retention_score AS retentionScore,
|
|
610
610
|
access_count AS accessCount,
|
|
@@ -617,7 +617,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
617
617
|
WHERE retention_score < ?
|
|
618
618
|
ORDER BY retention_score ASC,
|
|
619
619
|
COALESCE(last_accessed_at, created_at) ASC,
|
|
620
|
-
entry_id ASC`),
|
|
620
|
+
entry_id ASC`),f=e.prepare(`SELECT entry_id AS entryId,
|
|
621
621
|
tier,
|
|
622
622
|
retention_score AS retentionScore,
|
|
623
623
|
access_count AS accessCount,
|
|
@@ -631,7 +631,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
631
631
|
ORDER BY retention_score ASC,
|
|
632
632
|
COALESCE(last_accessed_at, created_at) ASC,
|
|
633
633
|
entry_id ASC
|
|
634
|
-
LIMIT ?`),
|
|
634
|
+
LIMIT ?`),p=e.prepare(`SELECT entry_id AS entryId,
|
|
635
635
|
tier,
|
|
636
636
|
retention_score AS retentionScore,
|
|
637
637
|
access_count AS accessCount,
|
|
@@ -645,7 +645,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
645
645
|
AND retention_score < ?
|
|
646
646
|
ORDER BY retention_score ASC,
|
|
647
647
|
COALESCE(last_accessed_at, created_at) ASC,
|
|
648
|
-
entry_id ASC`),
|
|
648
|
+
entry_id ASC`),te=e.prepare(`SELECT entry_id AS entryId,
|
|
649
649
|
tier,
|
|
650
650
|
retention_score AS retentionScore,
|
|
651
651
|
access_count AS accessCount,
|
|
@@ -660,4 +660,4 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
660
660
|
ORDER BY retention_score ASC,
|
|
661
661
|
COALESCE(last_accessed_at, created_at) ASC,
|
|
662
662
|
entry_id ASC
|
|
663
|
-
LIMIT ?`);return{create(e,n){t.run(e,n??`working`)},get(e){return n.get(e)},touch(e){r.run(e)},updateScore(e,t){i.run(t,e)},updateConfidence(e,t){a.run(t,e)},updateTier(e,t){o.run(t,t,t,e)},setSuperseded(e,t){s.run(t,e)},list(e){return e?.tier!==void 0&&e?.belowScore!==void 0&&e?.limit!==void 0?
|
|
663
|
+
LIMIT ?`);return{create(e,n){t.run(e,n??`working`)},get(e){return n.get(e)},touch(e){r.run(e)},updateScore(e,t){i.run(t,e)},updateConfidence(e,t){a.run(t,e)},updateTier(e,t){o.run(t,t,t,e)},setSuperseded(e,t){s.run(t,e)},list(e){return e?.tier!==void 0&&e?.belowScore!==void 0&&e?.limit!==void 0?te.all(e.tier,e.belowScore,e.limit):e?.tier!==void 0&&e?.belowScore!==void 0?p.all(e.tier,e.belowScore):e?.tier!==void 0&&e?.limit!==void 0?d.all(e.tier,e.limit):e?.tier===void 0?e?.belowScore!==void 0&&e?.limit!==void 0?f.all(e.belowScore,e.limit):e?.belowScore===void 0?e?.limit===void 0?c.all():l.all(e.limit):ee.all(e.belowScore):u.all(e.tier)}}}function pt(e){let t=Q(e)?tt(e):st(e),n=Q(e)?it(e):ut(e),r=Q(e)?at(e):dt(e),i=Q(e)?rt(e):lt(e),a=Q(e)?nt(e):ct(e),o=Q(e)?ot(e):ft(e);return{stashGet(e){return t.get(e)?.value},stashSet(e,n){t.set(e,n)},stashList(){return t.list()},stashDelete(e){return t.has(e)?(t.delete(e),!0):!1},stashClear(){t.clear()},signalPost(e,t,r,i,a){return n.post(e,t,r,i,a)},signalGet(e,t){return n.cleanExpired(),n.get(e,t).map(e=>({id:e.id,value:e.value,createdAt:Z(e.createdAt),expiresAt:Z(e.expiresAt),...e.agent?{agent:e.agent}:{}}))},signalList(e){return n.cleanExpired(),n.list(e).map(e=>({id:e.id,key:e.key,value:e.value,createdAt:Z(e.createdAt),...e.agent?{agent:e.agent}:{}}))},signalClear(e,t){return n.cleanExpired(),n.clear(e,t)},signalCleanExpired(){return n.cleanExpired()},leaseAcquire(e,t,n,i,a){r.cleanExpired();let o=r.get(e,n);return o&&o.holder!==t?!1:(r.upsert(e,t,n,i??o?.intent??void 0,a),!0)},leaseRelease(e,t,n){r.cleanExpired();let i=r.get(e,n);return!i||i.holder!==t?!1:(r.delete(e,n),!0)},leaseGet(e,t){r.cleanExpired();let n=r.get(e,t);if(n)return{resource:n.resource,holder:n.holder,workspace:n.workspace,acquiredAt:Z(n.acquiredAt),expiresAt:Z(n.expiresAt),...n.intent?{intent:n.intent}:{}}},leaseList(e){return r.cleanExpired(),r.list(e).map(e=>({resource:e.resource,holder:e.holder,acquiredAt:Z(e.acquiredAt),expiresAt:Z(e.expiresAt),...e.intent?{intent:e.intent}:{}}))},leaseCleanExpired(){return r.cleanExpired()},sessionCreate(e,t){i.create(e,t?JSON.stringify(t):void 0)},sessionTouch(e){i.touch(e)},sessionGet(e){let t=i.get(e);if(t)return{sessionId:t.sessionId,createdAt:t.createdAt,lastActivity:t.lastActivity,...t.metadata?{metadata:t.metadata}:{}}},sessionList(){return i.list().map(e=>({sessionId:e.sessionId,createdAt:e.createdAt,lastActivity:e.lastActivity}))},sessionDelete(e){return i.has(e)?(i.delete(e),!0):!1},sessionDeleteStale(e){return i.deleteStale(e)},checkpointSave(e,t,n,r){a.save(e,t,n,r)},checkpointLoad(e){let t=a.get(e);if(t)return{id:t.id,label:t.label,data:t.data,createdAt:t.createdAt,...t.notes?{notes:t.notes}:{}}},checkpointList(e,t){return a.list(e,t).map(e=>({id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}))},checkpointLatest(e){let t=a.latest(e);if(t)return{id:t.id,label:t.label,data:t.data,createdAt:t.createdAt,...t.notes?{notes:t.notes}:{}}},checkpointDelete(e){return a.has(e)?(a.delete(e),!0):!1},checkpointDiff(e,t){let n=a.get(e),r=a.get(t);if(!(!n||!r))return{from:n.data,to:r.data}},checkpointHistory(e,t){return a.list(e,t).map(e=>({id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}))},checkpointGc(e,t){return a.gc(e,t)},memoryMetaCreate(e,t){o.create(e,t)},memoryMetaGet(e){return o.get(e)},memoryMetaTouch(e){o.touch(e)},memoryMetaUpdateScore(e,t){o.updateScore(e,t)},memoryMetaUpdateConfidence(e,t){o.updateConfidence(e,t)},memoryMetaUpdateTier(e,t){o.updateTier(e,t)},memoryMetaSetSuperseded(e,t){o.setSuperseded(e,t)},memoryMetaList(e){return o.list(e)}}}var mt=ae({NodeSqliteAdapter:()=>ht}),ht=class{type=`node-sqlite`;kind=`node-sqlite`;_sqliteVecLoaded=!1;get vectorCapable(){return this._sqliteVecLoaded}get capabilities(){return{vectorCapable:this.vectorCapable,persistentFile:!0,concurrentReaders:!0}}db=null;getDb(){if(!this.db)throw Error(`NodeSqliteAdapter: database not opened`);return this.db}ensureOpen(){this.getDb()}async open(e){let t=m(e);t&&!c(t)&&l(t,{recursive:!0});let n;try{let e=await import(`node:sqlite`);if(!ye(e.DatabaseSync))throw Error(`node:sqlite DatabaseSync extension loading APIs are unavailable`);n=e.DatabaseSync}catch(e){throw Error(`node:sqlite unavailable (requires Node ≥22.13): ${e instanceof Error?e.message:String(e)}`)}this.db=new n(e,{allowExtension:!0,timeout:5e3});try{this.loadSqliteVec(),this.getDb().exec(`PRAGMA foreign_keys = ON`),this.getDb().exec(`PRAGMA journal_mode = WAL`),this.getDb().exec(`PRAGMA synchronous = NORMAL`),this.getDb().exec(`PRAGMA busy_timeout = 5000`)}finally{this.getDb().enableLoadExtension(!1)}}exec(e){this.ensureOpen(),this.getDb().exec(e)}pragma(e){this.ensureOpen(),this.getDb().exec(`PRAGMA ${e}`)}bindArgs(e){return e===void 0?[]:Array.isArray(e)?e:[e]}queryAll(e,t){return this.all(e,t)}get(e,t){this.ensureOpen();let n=this.getDb().prepare(e),r=this.bindArgs(t),i=r.length>0?n.get(...r):n.get();if(i!=null)return this.normalizeRow(i)}all(e,t){this.ensureOpen();let n=this.getDb().prepare(e),r=this.bindArgs(t);return(r.length>0?n.all(...r):n.all()).map(e=>this.normalizeRow(e))}run(e,t){this.ensureOpen();let n=this.getDb().prepare(e),r=this.bindArgs(t),i=r.length>0?n.run(...r):n.run();return{changes:i.changes,lastInsertRowid:i.lastInsertRowid}}transaction(e){this.ensureOpen(),this.getDb().exec(`BEGIN IMMEDIATE`);let t={exec:e=>{this.ensureOpen(),this.getDb().exec(e)},get:(e,t)=>{this.ensureOpen();let n=this.getDb().prepare(e),r=this.bindArgs(t),i=r.length>0?n.get(...r):n.get();if(i!=null)return this.normalizeRow(i)},all:(e,t)=>{this.ensureOpen();let n=this.getDb().prepare(e),r=this.bindArgs(t);return(r.length>0?n.all(...r):n.all()).map(e=>this.normalizeRow(e))},run:(e,t)=>{this.ensureOpen();let n=this.getDb().prepare(e),r=this.bindArgs(t),i=r.length>0?n.run(...r):n.run();return{changes:i.changes,lastInsertRowid:i.lastInsertRowid}}};try{let n=e(t);return this.getDb().exec(`COMMIT`),n}catch(e){try{this.getDb().exec(`ROLLBACK`)}catch{}throw e}}flush(){}async close(){this.db&&=(this.getDb().close(),null)}normalizeRow(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t=e;for(let e of Object.keys(t)){let n=t[e];Buffer.isBuffer(n)&&(t[e]=new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}return e}loadSqliteVec(){try{let e=be();if(!e)throw Error(`Could not locate sqlite-vec extension binary`);if(this.getDb().enableLoadExtension(!0),this.getDb().loadExtension(e),!this.getDb().prepare(`SELECT vec_version() AS version`).get()?.version)throw Error(`sqlite-vec loaded but vec_version() returned no data`);let t=new Uint8Array(new Float32Array([1,0,0]).buffer),n=new Uint8Array(new Float32Array([0,1,0]).buffer),r=this.getDb().prepare(`SELECT vec_distance_cosine(?, ?) AS d`).get(t,n);if(!r||typeof r.d!=`number`)throw Error(`sqlite-vec smoke test failed: unexpected result ${JSON.stringify(r)}`);this._sqliteVecLoaded=!0}catch(e){this._sqliteVecLoaded=!1,console.warn(`[NodeSqliteAdapter] sqlite-vec loading failed, vector search disabled:`,e instanceof Error?e.message:String(e))}}};const $=a(`store-factory`);async function gt(e){if(e.adapter)return{adapter:e.adapter,selection:null};let t=e.sqliteDriver??process.env.AI_KIT_SQLITE_DRIVER??`auto`,n=e.allowFallback??process.env.AI_KIT_SQLITE_ALLOW_FALLBACK!==`false`,r;try{r=await P({driver:t,databasePath:e.path})}catch(i){if(n&&t!==`auto`)$.warn(`Forced driver "${t}" failed — falling back to auto selection`),r=await P({databasePath:e.path});else throw i}let i;switch(r.kind){case`node-sqlite`:i=new ht;break;case`better-sqlite3`:i=new E;break;case`sqljs`:i=new F;break;default:{let e=r.kind;throw Error(`Unknown driver kind: ${e}`)}}if($.debug(`Storage backend: ${r.kind}`),r.failures.length>0){$.warn(`Fallback reasons:`);for(let e of r.failures)$.warn(` ${e.driver}: ${e.code} — ${e.message}`)}return{adapter:i,selection:r}}async function _t(e){switch(e.backend){case`lancedb`:{let{LanceStore:t}=await import(`./lance-store-B1Gim3h9.js`);return new t({path:e.path})}case`sqlite-vec`:{let{adapter:t}=await gt(e);return new Qe({path:e.path,adapter:t,embeddingDim:e.embeddingDim,embeddingProfile:e.embeddingProfile,partition:e.partition})}default:{let t=e.backend;throw Error(`Unknown store backend: "${t}". Supported: lancedb, sqlite-vec`)}}}export{z as CONTROL_TABLES,He as SqliteGraphStore,Qe as SqliteVecStore,_ as allMigrations,Ae as createSqlJsAdapter,L as createSqliteAdapter,pt as createStateStore,_t as createStore,Me as getTablePartition,Ve as migrateToSplitState,Ne as readStatePartitionConfigFromEnv,B as resolveStatePartitionConfig,g as runMigrations};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import{AGENTS as e}from"../definitions/agents.mjs";import{AGENT_BODIES as t}from"../definitions/bodies.mjs";import{VARIANT_GROUPS as n,getPrimaryAgentModel as r}from"../definitions/models.mjs";import{PROMPTS as i}from"../definitions/prompts.mjs";import{AIKIT_INSTALL_HINT_SECTION as a,PLATFORM_OUTPUT_RULES_SECTION as o,PROTOCOLS as s,TEMPLATES as c}from"../definitions/protocols.mjs";import{IDE_CAPABILITIES as l}from"../definitions/tools.mjs";import{buildCompactAgentTable as u}from"./_shared.mjs";import{generateHooks as d,getHookScriptFiles as f}from"./hooks.mjs";import{generateForbiddenTable as p}from"../definitions/policies.mjs";const m={terminal:`terminal`,problems:`mcp_aikit_check`,readFile:`read_file`,lastCommand:`terminal`,subagent:`delegate_task`,createFile:`write_file`,editFiles:`patch`,rename:`write_file`,createDirectory:`terminal(mkdir)`,search:`search_files, mcp_aikit_search, mcp_aikit_find`,web:`web_search, web_extract, mcp_aikit_web_search, mcp_aikit_web_fetch`,todo:`todo`,memory:`memory`,newWorkspace:`terminal(cd)`,reviewPlan:`clarify`,askQuestions:`clarify`,resolveMemoryFileUri:`read_file`,runCommand:`terminal`,switchAgent:`delegate_task`,killTerminal:`process(kill)`,createTask:`todo`,terminalSel:`terminal`,fileSearch:`search_files`,listDir:`search_files(target=files)`,textSearch:`search_files(target=content)`,searchSubagent:`delegate_task`,browser:`mcp_aikit_browser, browser_navigate`};function h(e){let t=[[/`runSubagent`/g,"`delegate_task`"],[/`runSubagent\(/g,"`delegate_task("],[/\brunSubagent\b/g,`delegate_task`],[/`editFiles`/g,"`patch`"],[/`createFile`/g,"`write_file`"],[/`edit\/createFile`/g,"`write_file`"],[/`edit\/editFiles`/g,"`patch`"],[/`run_in_terminal`/g,"`terminal`"],[/`execute\/runInTerminal`/g,"`terminal`"],[/`execute\/killTerminal`/g,"`process(kill)`"],[/`grep_search`/g,"`search_files`"],[/`search\/codebase`/g,"`mcp_aikit_search`"],[/`search\/changes`/g,"`search_files`"],[/`search\/usages`/g,"`mcp_aikit_symbol` / `mcp_aikit_trace`"],[/`search\/textSearch`/g,"`search_files`"],[/`search\/searchSubagent`/g,"`delegate_task`"],[/`web\/fetch`/g,"`web_extract` / `mcp_aikit_web_fetch`"],[/`web\/githubRepo`/g,"`terminal(git ...)`"],[/`web\/webSearch`/g,"`web_search` / `mcp_aikit_web_search`"],[/`vscode\/memory`/g,"`memory`"],[/`vscode\/runCommand`/g,"`terminal`"],[/`vscode\/switchAgent`/g,"`delegate_task`"],[/`vscode\/newWorkspace`/g,"`terminal(cd)`"],[/`vscode\/reviewPlan`/g,"`clarify`"],[/`vscode\/askQuestions`/g,"`clarify`"],[/`vscode\/resolveMemoryFileUri`/g,"`read_file`"],[/`read\/readFile`/g,"`read_file`"],[/`read\/terminalLastCommand`/g,"`terminal`"],[/`read\/terminalSelection`/g,"`terminal`"],[/`read\/problems`/g,"`mcp_aikit_check`"],[/`agent\/runSubagent`/g,"`delegate_task`"],[/`execute\/createAndRunTask`/g,"`todo` / `delegate_task`"],[/`read_file` \(for understanding\)/g,"`read_file` (Hermes)"],[/\(copilot\)/g,`(hermes)`],[/runSubagent\(\{agentName:/g,`delegate_task({goal:`],[/runSubagent\(\{/g,`delegate_task({`]],n=e;for(let[e,r]of t)n=n.replace(e,r);return n}function g(e){let t=(l[e]||[]).map(e=>{let t=m[e];return t?t.split(`,`).map(e=>e.trim()):null}).filter(Boolean).flat();return`[${[...new Set(t),`aikit/*`].join(`, `)}]`}function _(e){return r(`hermes`,e,`Auto (hermes)`)}const v=[`## Flows`,``,"This project uses aikit's pluggable flow system. Check flow status with the `flow` or `mcp_aikit_flow` MCP tool.","If a flow is active, follow the current step's skill instructions. Advance with `mcp_aikit_flow({ action: 'step', advance: 'next' })`.","Use `mcp_aikit_flow({ action: 'list' })` to see available flows and `mcp_aikit_flow({ action: 'start', name, topic })` to begin one."].join(`
|
|
2
|
+
`),y=[`## Flows`,``,"This project uses aikit's pluggable flow system. Use `mcp_aikit_flow({ action: 'status' })` to check if a flow is active.",`If dispatched as part of a flow, your work contributes to the current step. Do NOT advance or manage the flow — the Orchestrator handles flow lifecycle.`].join(`
|
|
3
|
+
`);function b(){let t=[];for(let[i,a]of Object.entries(e))if(a.variants)for(let e of n[i]||[]){let n=`${i}-${e}`,o=r(`hermes`,n,`Unknown`),s=(a.variants[e]||{}).description||a.description;t.push(`| **${n}** | ${s} | ${o} | ${a.category} |`)}else{let e=r(`hermes`,i,`Unknown`);t.push(`| **${i}** | ${a.description} | ${e} | ${a.category} |`)}return`| Agent | Purpose | Model | Category |\n|-------|---------|-------|----------|\n${t.join(`
|
|
4
|
+
`)}`}function x(e,t,r){let i=`${e}-${t}`,a=r.variants[t]||{},o=_(i),c=a.description||r.description,l=a.identity||(t===n[e]?.[0]?`, the primary ${e} agent.`:`, a variant of ${e}. Same responsibilities, different model perspective.`),u=r.sharedBase&&s[r.sharedBase]?`\n\n${s[r.sharedBase]}`:``;u=h(u);let d=r.extraBody?`\n\n${h(r.extraBody)}`:``,f=a.bodyAddendum?`\n\n${h(a.bodyAddendum)}`:``,p=(r.sharedProtocols||[]).map(e=>{let t=s[e];return t?`\n\n${h(t)}`:``}).join(``),m=r.skills?.length?`\n\n## Skills (load on demand)\n\n${r.skills.map(([e,t])=>`- \`${e}\`: ${t}`).join(`
|
|
5
|
+
`)}`:``,v=r.title||e;return`---
|
|
6
|
+
description: '${c}'
|
|
7
|
+
${r.argumentHint?`argument-hint: "${r.argumentHint}"\n`:``}tools: ${g(r.toolRole)}
|
|
8
|
+
model: ${o}
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# ${i} - ${v}
|
|
12
|
+
|
|
13
|
+
You are **${i}**${l}${d}
|
|
14
|
+
${u}${p}${f}${m}
|
|
15
|
+
|
|
16
|
+
${y}
|
|
17
|
+
`}function S(n,r){let i=_(n),a=typeof t[n]==`function`?t[n](u(e)):t[n]||``;a=h(a);let o=r.sharedBase&&s[r.sharedBase]?`\n\n${s[r.sharedBase]}`:``;o=h(o);let c=(r.sharedProtocols||[]).map(e=>{let t=s[e];return t?`\n\n${h(t)}`:``}).join(``),l=r.title||n,d=r.skills?.length?`\n## Skills (load on demand)\n\n${r.skills.map(([e,t])=>`- \`${e}\`: ${t}`).join(`
|
|
18
|
+
`)}\n`:``;return`---
|
|
19
|
+
description: '${r.description}'
|
|
20
|
+
${r.argumentHint?`argument-hint: "${r.argumentHint}"\n`:``}tools: ${g(r.toolRole)}
|
|
21
|
+
model: ${i}
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
# ${n} - ${l}
|
|
25
|
+
|
|
26
|
+
You are the **${n}**, ${r.description.toLowerCase().replace(/^./,e=>e.toLowerCase())}
|
|
27
|
+
|
|
28
|
+
${a}${o}${c}${d}
|
|
29
|
+
|
|
30
|
+
${n===`Orchestrator`?v:y}
|
|
31
|
+
`}function C(e,t){return`---
|
|
32
|
+
description: "${t.description}"
|
|
33
|
+
agent: "${t.agent}"
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
${t.content}
|
|
37
|
+
`}function w(){return`# Hermes Agents
|
|
38
|
+
|
|
39
|
+
This directory contains AI agent definitions generated by \`@vpxa/aikit init\` for **Hermes Agent**.
|
|
40
|
+
|
|
41
|
+
## Agent Roster
|
|
42
|
+
|
|
43
|
+
${b()}
|
|
44
|
+
|
|
45
|
+
## Multi-Model Pattern
|
|
46
|
+
|
|
47
|
+
Variant agents (Researcher-Alpha/Beta/Gamma/Delta, Code-Reviewer-Alpha/Beta, Architect-Reviewer-Alpha/Beta) share the same methodology via files in \`_shared/\`. They differ only in which LLM model backs them — enabling multi-model decision analysis and dual-review workflows.
|
|
48
|
+
|
|
49
|
+
## Tools
|
|
50
|
+
|
|
51
|
+
Hermes provides native tools (\`terminal\`, \`read_file\`, \`write_file\`, \`patch\`, \`search_files\`, \`delegate_task\`, etc.)
|
|
52
|
+
plus AI Kit MCP tools (\`mcp_aikit_search\`, \`mcp_aikit_knowledge\`, etc.) for code analysis, memory, and context compression.
|
|
53
|
+
|
|
54
|
+
See \`AGENTS.md\` (in Hermes config directory) for complete tool usage guidance.
|
|
55
|
+
`}function T(){return[`# aikit — Hermes Agent Instructions`,``,"This file is generated from `scaffold/definitions/`. Do not edit directly.",``,o,``,`## Tool Routing Rules`,``,`Hermes provides native tools (terminal, read_file, write_file, patch, search_files, delegate_task, etc.)`,`plus AI Kit MCP tools (mcp_aikit_*) for code analysis, memory, and context compression.`,``,`### When to Use AI Kit Tools`,``,`| Instead of | Use AI Kit Tool | Why |`,`|-----------|----------------|-----|`,"| `grep` / `rg` | `mcp_aikit_search` or `mcp_aikit_find` | Hybrid search across all indexed content |","| `cat` for understanding | `mcp_aikit_file_summary` or `mcp_aikit_compact` | 10x fewer tokens than raw file reads |","| Running tests in terminal | `mcp_aikit_test_run` | Structured output — no shell needed |","| `tsc` / `biome` in terminal | `mcp_aikit_check` | Typecheck + lint combined |","| Web search | `mcp_aikit_web_search` | Fans out to multiple keyless providers |",``,p(),``,a,``].join(`
|
|
56
|
+
`)}function E(){let t=[];if(f().length===0)throw Error(`Executable hooks are not configured.`);t.push({path:`hermes-instructions.md`,content:T()});for(let[r,i]of Object.entries(e))if(i.variants)for(let e of n[r]||[])t.push({path:`agents/${r}-${e}.agent.md`,content:x(r,e,i)});else t.push({path:`agents/${r}.agent.md`,content:S(r,i)});for(let[e,n]of Object.entries(s))t.push({path:`agents/_shared/${e}.md`,content:`${h(n)}\n`});for(let[e,n]of Object.entries(c))t.push({path:`agents/templates/${e}.md`,content:`${n}\n`});t.push({path:`agents/README.md`,content:w()});for(let[e,n]of Object.entries(i))t.push({path:`prompts/aikit-${e}.prompt.md`,content:C(e,n)});let r=d(`hermes`,`~/.hermes/hooks/scripts`);return t.push(...r.map(e=>({path:`hooks/${e.path}`,content:e.content}))),t}export{E as generateHermesAgent};
|