@vpxa/aikit 0.1.368 → 0.1.370
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/claude-desktop/dist/manifest.json +1 -1
- package/packages/cli/dist/index.js +2 -2
- package/packages/cli/dist/{init-DVXEzLeU.js → init-Bt7plNS5.js} +1 -1
- package/packages/server/dist/bin.js +1 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/prelude-CP2KyUi7.js +1 -0
- package/packages/server/dist/prelude-DKiNtmXm.js +2 -0
- package/packages/server/dist/sampling-C-jvG_Pm.js +2 -0
- package/packages/server/dist/sampling-C6IpmdTS.js +1 -0
- package/packages/server/dist/{server-CQesOcq1.js → server-B6T0DJPk.js} +5 -5
- package/packages/server/dist/{server-DDHbLCBq.js → server-J1siOixh.js} +5 -5
- package/packages/server/dist/{server-http-6OV80fAK.js → server-http-BOP-H7O4.js} +1 -1
- package/packages/server/dist/{server-http-D_ho5y9i.js → server-http-DBODPVTO.js} +1 -1
- package/packages/server/dist/{server-stdio-DRUYwrAn.js → server-stdio-BwEcanZf.js} +1 -1
- package/packages/server/dist/{server-stdio-TTFGWi1g.js → server-stdio-iaR70OMP.js} +1 -1
- package/packages/server/dist/startup-maintenance-BPrX5-1U.js +2 -0
- package/packages/server/dist/startup-maintenance-CT6Z3734.js +1 -0
- package/packages/server/dist/version-check-C7xqQr9o.js +1 -0
- package/packages/server/dist/version-check-CH5SIhnq.js +2 -0
- package/packages/store/dist/index.js +2 -2
- package/scaffold/dist/adapters/claude-code.mjs +7 -7
- package/packages/server/dist/prelude-9_sq1gWj.js +0 -1
- package/packages/server/dist/prelude-C229S1cr.js +0 -2
- package/packages/server/dist/sampling-BLUbfYBk.js +0 -1
- package/packages/server/dist/sampling-Xji5tTKx.js +0 -2
- package/packages/server/dist/startup-maintenance-CBJWiJ7p.js +0 -2
- package/packages/server/dist/startup-maintenance-DX1yTfBa.js +0 -1
- package/packages/server/dist/version-check-CRvtGBDG.js +0 -2
- package/packages/server/dist/version-check-DNe43rCZ.js +0 -1
|
@@ -111,7 +111,7 @@ 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(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 Pe=`_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),L(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 Re(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${V(t)}`)[0]?.count??0}function ze(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 Be(e){e.exec(`
|
|
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,{timeout:5e3}),this.dbPath=t,this.DatabaseCtor=n,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`),this.db.pragma(`busy_timeout = 5000`),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,{timeout:5e3}),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 Pe=`_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),L(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 Re(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${V(t)}`)[0]?.count??0}function ze(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 Be(e){e.exec(`
|
|
115
115
|
CREATE TABLE IF NOT EXISTS ${Pe} (
|
|
116
116
|
key TEXT PRIMARY KEY,
|
|
117
117
|
value TEXT NOT NULL,
|
|
@@ -121,7 +121,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
|
|
|
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 He(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 H(n.contentDbPath),i=await H(n.controlDbPath);try{g(i,_);let e=[];for(let t of z){if(!U(r,t))continue;ze(r,i,t);let n=Re(r,t),a=Re(i,t);if(a<n)throw Error(`Split-state migration verification failed for ${t}: source=${n} target=${a}`);e.push(t)}Ve(i,n,e)}finally{r.close(),i.close()}}var Ue=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(`
|
|
124
|
+
updated_at = datetime('now')`,[`split-state`,JSON.stringify({splitEnabled:t.splitEnabled,contentDbPath:t.contentDbPath,controlDbPath:t.controlDbPath,migratedTables:n})])}async function He(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 H(n.contentDbPath),i=await H(n.controlDbPath);try{g(i,_);let e=[];for(let t of z){if(!U(r,t))continue;ze(r,i,t);let n=Re(r,t),a=Re(i,t);if(a<n)throw Error(`Split-state migration verification failed for ${t}: source=${n} target=${a}`);e.push(t)}Ve(i,n,e)}finally{r.close(),i.close()}}var Ue=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`),e.pragma(`busy_timeout = 5000`)}createTables(e){e.exec(`
|
|
125
125
|
CREATE TABLE IF NOT EXISTS nodes (
|
|
126
126
|
id TEXT PRIMARY KEY,
|
|
127
127
|
type TEXT NOT NULL,
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{AGENTS as e}from"../definitions/agents.mjs";import{AGENT_BODIES as t}from"../definitions/bodies.mjs";import{HOOKS as n}from"../definitions/hooks.mjs";import{
|
|
2
|
-
`)}function
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function
|
|
5
|
-
`)}function
|
|
1
|
+
import{AGENTS as e}from"../definitions/agents.mjs";import{AGENT_BODIES as t}from"../definitions/bodies.mjs";import{HOOKS as n}from"../definitions/hooks.mjs";import{SERVER_NAME as r}from"../definitions/mcp.mjs";import{getPlatformPrimaryModelMap as i}from"../definitions/models.mjs";import{PLATFORM_HOOK_CAPABILITIES as a}from"../definitions/platform-capabilities.mjs";import{PROMPTS as o}from"../definitions/prompts.mjs";import{AIKIT_INSTALL_HINT_SECTION as s,PLATFORM_OUTPUT_RULES_SECTION as c,PROTOCOLS as l}from"../definitions/protocols.mjs";import{AIKIT_TOOLS as u,CLAUDE_CODE_TOOL_MAP as d,IDE_CAPABILITIES as f}from"../definitions/tools.mjs";import{buildAgentTable as p,buildCompactAgentTable as m,buildFlowSection as h,buildHooksSection as g,buildSkillsSection as _,injectOrchestratorDirective as v,lowerFirst as y}from"./_shared.mjs";const b=h({flowTool:`flow`,isLifecycleOwner:!0}),x=h({flowTool:`flow`,isLifecycleOwner:!0}),S=h({flowTool:`flow`,isLifecycleOwner:!1});function C(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).replace(/[^a-zA-Z0-9]+/g,`-`).replace(/^-+|-+$/g,``).toLowerCase()}function w(e){return`"${String(e).replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function T(e){let t=(f[e]||[]).flatMap(e=>d[e]||[]),n=u.map(e=>`mcp__${r.toLowerCase().replace(/[^a-z0-9]/g,``)}__${e}`);return[...new Set([...t,...n])].sort((e,t)=>e.localeCompare(t))}function E(e,t){let n=[];return n.push(`# ${r} ${e}`),n.push(``),t.description&&(n.push(`> ${t.description}`),n.push(``)),n.push(t.content.trim()),n.push(``),n.join(`
|
|
2
|
+
`)}function D(e,n){let r=t[e];return typeof r==`function`?r(n):r||``}function O(e){let t=[];e.extraBody&&t.push(e.extraBody),e.sharedBase&&l[e.sharedBase]&&t.push(l[e.sharedBase]);for(let n of e.sharedProtocols||[])l[n]&&t.push(l[n]);return t}function k(){let t=[];for(let[n,r]of Object.entries(e)){if(r.variants){for(let[e,i]of Object.entries(r.variants))t.push({name:`${n}-${e}`,description:i.description||r.description});continue}t.push({name:n,description:r.description})}return t}function A(e){return k().map(({name:t,description:n})=>`- \`${e}/${t}.md\` — ${n}`).join(`
|
|
3
|
+
`)}function j(t=p(e,i(`claude-code`))){return[`# ${r} — Claude Code Agents`,``,c,``,s,``,`## MCP Server`,``,`Server name: \`${r}\``,"Configured in `.mcp.json` (project) and `~/.claude.json` (user-global — `claude mcp add --scope user` format).","Default agent: `Orchestrator` in `~/.claude/settings.json` — every conversation starts as Orchestrator automatically.",``,`## Agents`,``,t,``,`## Agent Files`,``,A(`.claude/agents`),``,`## Commands`,``,"Slash commands live under `.claude/commands/`.",``,`## Session Protocol`,``,g(n,a[`claude-code`]),``].join(`
|
|
4
|
+
`)}function M(){return v([`# ${r} — Claude Code Instructions`,``,"Detailed workspace instructions live in `AGENTS.md`.","Full sub-agent instructions live in `.claude/agents/`.","Slash commands live in `.claude/commands/`.","MCP server config lives in `.mcp.json` (project) and `~/.claude.json` (user-global — written by `claude mcp add --scope user`).","Default agent set to `Orchestrator` in `~/.claude/settings.json` — every conversation starts as Orchestrator, no `/agent` command needed.",``,"Start with `AGENTS.md`, then open the specific sub-agent file you want to use.",``,c,``,s,``]).join(`
|
|
5
|
+
`)}function N(e,t,n,i,a){let o=T(t.toolRole),s=O(t),c=_(t.skills),l=e===`Orchestrator`?[b,x]:[S],u=[n,...s,t.bodyAddendum,c,...l].filter(Boolean).join(`
|
|
6
6
|
|
|
7
|
-
`).trim(),d=t.identity?`You are the **${e}**${t.identity}`:`You are the **${e}**, ${
|
|
8
|
-
`)}function
|
|
7
|
+
`).trim(),d=t.identity?`You are the **${e}**${t.identity}`:`You are the **${e}**, ${y(t.description)}.`,f=a?.[e],p=o.length>0?`tools: [${o.join(`, `)}]`:null,m=t.skills?.length>0?`skills: [${t.skills.map(([e])=>e).join(`, `)}]`:null,h=[`---`,`name: ${C(e)}`,`description: ${w(t.description)}`,...f?[`model: ${w(f)}`]:[],...p?[p]:[],`mcpServers:`,` - ${r}`,...m?[m]:[],`---`,``,`# ${e} - ${t.title||e}`,``,d];return u&&h.push(``,u),h.push(``),h.join(`
|
|
8
|
+
`)}function P(){let t=[],n=i(`claude-code`),r=p(e,n),a=m(e);t.push({path:`CLAUDE.md`,content:M()}),t.push({path:`AGENTS.md`,content:j(r)});for(let[e,n]of Object.entries(o))t.push({path:`.claude/commands/aikit-${e}.md`,content:E(e,n)});for(let[i,o]of Object.entries(e)){let e=D(i,a);if(o.variants){for(let[a,s]of Object.entries(o.variants)){let c=`${i}-${a}`;t.push({path:`.claude/agents/${c}.md`,content:N(c,{...o,description:s.description||o.description,identity:s.identity,bodyAddendum:s.bodyAddendum},e,r,n)})}continue}t.push({path:`.claude/agents/${i}.md`,content:N(i,o,e,r,n)})}return t}export{b as CLAUDE_FLOWS_SECTION,x as CLAUDE_ORCHESTRATOR_FLOW_ROUTING_SECTION,P as generateClaudeCode};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./server-CQesOcq1.js";export{t as buildPreludeInjection,e as generatePrelude};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./server-CQesOcq1.js";export{e as createSamplingClient};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{t as e}from"./bin.js";import{createLogger as t,serializeError as n}from"../../core/dist/index.js";const r=t(`server`);function i(e,t){return t?{version:e,...n(t)}:{version:e}}function a(t,a,o){t.then(async()=>{try{let{markPromoteRun:t,markPruneRun:n,prune:i,shouldRunStartupPrune:o,shouldRunWeeklyPromote:s}=await import(`../../tools/dist/index.js`),c=a();if(!c)return;if(o()){let e=await i({});n(),e.totalBytesFreed>0&&r.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:a}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),o=await a(c.curated,c.stateStore,{dryRun:!1});o.pruned.length>0&&r.info(`Startup lesson prune complete`,{pruned:o.pruned.length});let s=await t(c.curated,c.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&r.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(s()){let{DEFAULT_PROMOTE_CONFIG:n,collectWorkspaceLessons:i,getGlobalCuratedDir:a,promoteLessons:o,scanForDuplicates:s}=await import(`./promotion-DRnRfteq.js`).then(e=>e.o),l=c.curated,u=new e(a(),l.store,l.embedder),d=await i(),f={...n,dryRun:!1},p=await o(s(d,f),u,f);t(),p.promoted.length>0&&r.info(`Weekly lesson promotion complete`,{promoted:p.promoted.length,candidates:p.candidates.length})}}catch(e){r.warn(`Startup maintenance failed (non-critical)`,i(o,e))}}).catch(e=>r.warn(`Startup maintenance failed`,n(e)))}export{i as n,a as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./curated-manager-CBKTmAjM.js";import{createLogger as t,serializeError as n}from"../../core/dist/index.js";const r=t(`server`);function i(e,t){return t?{version:e,...n(t)}:{version:e}}function a(t,a,o){t.then(async()=>{try{let{markPromoteRun:t,markPruneRun:n,prune:i,shouldRunStartupPrune:o,shouldRunWeeklyPromote:s}=await import(`../../tools/dist/index.js`),c=a();if(!c)return;if(o()){let e=await i({});n(),e.totalBytesFreed>0&&r.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:a}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),o=await a(c.curated,c.stateStore,{dryRun:!1});o.pruned.length>0&&r.info(`Startup lesson prune complete`,{pruned:o.pruned.length});let s=await t(c.curated,c.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&r.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(s()){let{DEFAULT_PROMOTE_CONFIG:n,collectWorkspaceLessons:i,getGlobalCuratedDir:a,promoteLessons:o,scanForDuplicates:s}=await import(`./promotion-DzVLWVtx.js`).then(e=>e.o),l=c.curated,u=new e(a(),l.store,l.embedder),d=await i(),f={...n,dryRun:!1},p=await o(s(d,f),u,f);t(),p.promoted.length>0&&r.info(`Weekly lesson promotion complete`,{promoted:p.promoted.length,candidates:p.candidates.length})}}catch(e){r.warn(`Startup maintenance failed (non-critical)`,i(o,e))}}).catch(e=>r.warn(`Startup maintenance failed`,n(e)))}export{i as n,a as t};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{fileURLToPath as e}from"node:url";import{INSTALL_ARGS as t,cleanupOldVersions as n,createLogger as r,safeCwd as i}from"../../core/dist/index.js";import{existsSync as a,mkdirSync as o,readFileSync as s,renameSync as c,rmSync as l,writeFileSync as u}from"node:fs";import{dirname as d,join as f,resolve as p}from"node:path";import{homedir as m}from"node:os";import{execFile as h,execSync as g,spawn as _}from"node:child_process";const v=`@vpxa/aikit`,y=`https://registry.npmjs.org/${v}/latest`,b=r(`server`);function x(){let t=d(e(import.meta.url));return[p(t,`..`,`..`,`..`,`bin`,`aikit.mjs`),p(t,`..`,`bin`,`aikit.mjs`),...process.argv[1]?[p(d(process.argv[1]),`aikit.mjs`)]:[]].find(e=>a(e))??null}const S=f(m(),`.aikit`),C=f(S,`current-version.json`),w=f(S,`versions`),T=/^\d+\.\d+\.\d+(-[\w.+]+)?(\+[\w.]+)?$/;function E(e){if(!T.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}function D(){let t=p(d(e(import.meta.url)),`..`,`..`,`..`,`package.json`);try{return JSON.parse(s(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function O(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t>0?1:-1}return 0}function k(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){if((n[e]??0)>(r[e]??0))return!0;if((n[e]??0)<(r[e]??0))return!1}return!1}function A(e){if(!a(e))return;for(let t=1;t<=2;t++)try{l(e,{recursive:!0,force:!0});return}catch(n){if(!(n.code===`EPERM`||n.code===`EBUSY`||/EPERM|permission denied/i.test(String(n)))){b.debug(`Failed to remove directory`,{path:e,error:n instanceof Error?n.message:String(n),attempt:t});return}}let t=`${e}.orphaned.${Date.now()}`;try{c(e,t),b.debug(`Renamed locked directory to ${t} — deferred cleanup`);try{l(t,{recursive:!0,force:!0})}catch{}}catch(t){b.debug(`Failed to rename locked directory`,{path:e,error:t instanceof Error?t.message:String(t)})}}async function j(e){E(e);let n=`v${e}`,r=f(w,`${n}-staging`),i=f(w,n);try{A(r),o(r,{recursive:!0}),g(`tar -xzf "${g(`npm pack ${v}@${e} 2>${process.platform===`win32`?`NUL`:`/dev/null`}`,{cwd:r,encoding:`utf-8`,timeout:6e4,windowsHide:!0}).trim()}"`,{cwd:r,encoding:`utf-8`,stdio:`pipe`,timeout:3e4,windowsHide:!0});let n=f(r,`package`);g(`npm ${t.join(` `)}`,{cwd:n,encoding:`utf-8`,stdio:`pipe`,timeout:12e4,windowsHide:!0});let s=f(n,`packages`,`server`,`dist`,`bin.js`);if(!a(s))throw Error(`Server entry not found at ${s}`);if(!a(f(n,`node_modules`)))throw Error(`node_modules not found — npm install may have failed`);a(i)&&l(i,{recursive:!0,force:!0}),c(n,i);let d=`${C}.tmp`;u(d,JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)),c(d,C),N(e)}finally{A(r)}}function M(e){b.debug(`Updated to v${e}. Restarting server...`),setTimeout(()=>{process.exit(0)},300).unref()}function N(e){n(w,e??D())}async function P(){try{let e=s(C,`utf-8`),{version:t}=JSON.parse(e),n=await fetch(y,{signal:AbortSignal.timeout(1e4)});if(!n.ok)return;let r=(await n.json()).version;if(!r||r===t||!k(r,t))return;if(a(f(w,`v${r}`))){let e=`${C}.tmp`;u(e,JSON.stringify({version:r,installedAt:new Date().toISOString()},null,2)),c(e,C),b.debug(`Re-activated existing version v${r} — no download needed`),M(r);return}b.debug(`New version available: ${r}. Installing...`),await j(r),M(r)}catch(e){b.error(`Background update check failed: ${e instanceof Error?e.message:String(e)}`)}}let F=null;function I(){return F||(F=L().finally(()=>{F=null}),F)}async function L(){if(a(C)){await P();return}let e=D();try{let t=await fetch(y,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return;let n=(await t.json()).version;if(!n)return;if(O(e,n)<0){b.debug(`Newer version available — installing`,{currentVersion:e,latestVersion:n});try{await j(n),M(n)}catch(e){b.warn(`Auto-install failed`,{error:e instanceof Error?e.message:String(e),latestVersion:n})}}}catch{}}function R(){try{let e=p(m(),`.copilot`,`.aikit-scaffold.json`);return a(e)?JSON.parse(s(e,`utf-8`)).version??null:null}catch{return null}}function z(){try{let e=i();if(!e)return null;let t=p(e,`.github`,`.aikit-scaffold.json`);return a(t)?JSON.parse(s(t,`utf-8`)).version??null:null}catch{return null}}let B=`idle`,V=null,H=null,U=!1;function W(){return{state:B,error:V}}function G(){B=`idle`,V=null}function K(){try{let e=D();if(I(),!U){U=!0;try{let e=x();e&&_(process.execPath,[e,`migrate-launcher`],{cwd:m(),stdio:`ignore`,timeout:15e3,windowsHide:!0}).unref()}catch{}}let t=R(),n=z();if(!(t!=null&&t!==e)&&!(n!=null&&n!==e)||(H!==e&&(G(),H=e),B!==`idle`))return;B=`pending`,V=null,b.debug(`Scaffold version mismatch — auto-upgrading`,{serverVersion:e,userScaffoldVersion:t,workspaceScaffoldVersion:n});let r=x();if(!r){B=`failed`,V=`aikit CLI binary not found`,b.warn(`Cannot auto-upgrade: aikit CLI binary not found`);return}let i=m();h(process.execPath,[r,`upgrade`],{cwd:i,timeout:3e4,windowsHide:!0},(t,n,a)=>{t?(B=`failed`,V=t.message,b.warn(`Auto-upgrade failed`,{error:t.message,stack:t.stack,code:t.code,stdout:n?.slice(0,500),stderr:a?.slice(0,500),cwd:i,binPath:r,platform:process.platform})):(B=`success`,V=null,b.debug(`Auto-upgrade completed to version ${e}`))}).unref()}catch(e){B=`failed`,V=e instanceof Error?e.message:String(e),b.warn(`Auto-upgrade check failed`,{error:V})}}export{K as autoUpgradeScaffold,I as checkForUpdates,N as cleanupOldVersions,D as getCurrentVersion,W as getUpgradeState};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{fileURLToPath as e}from"node:url";import{INSTALL_ARGS as t,cleanupOldVersions as n,createLogger as r,safeCwd as i}from"../../core/dist/index.js";import{existsSync as a,mkdirSync as o,readFileSync as s,renameSync as c,rmSync as l,writeFileSync as u}from"node:fs";import{dirname as d,join as f,resolve as p}from"node:path";import{execFile as m,execSync as h,spawn as g}from"node:child_process";import{homedir as _}from"node:os";const v=`@vpxa/aikit`,y=`https://registry.npmjs.org/${v}/latest`,b=r(`server`);function x(){let t=d(e(import.meta.url));return[p(t,`..`,`..`,`..`,`bin`,`aikit.mjs`),p(t,`..`,`bin`,`aikit.mjs`),...process.argv[1]?[p(d(process.argv[1]),`aikit.mjs`)]:[]].find(e=>a(e))??null}const S=f(_(),`.aikit`),C=f(S,`current-version.json`),w=f(S,`versions`),T=/^\d+\.\d+\.\d+(-[\w.+]+)?(\+[\w.]+)?$/;function E(e){if(!T.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}function D(){let t=p(d(e(import.meta.url)),`..`,`..`,`..`,`package.json`);try{return JSON.parse(s(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function O(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t>0?1:-1}return 0}function k(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){if((n[e]??0)>(r[e]??0))return!0;if((n[e]??0)<(r[e]??0))return!1}return!1}function A(e){if(!a(e))return;for(let t=1;t<=2;t++)try{l(e,{recursive:!0,force:!0});return}catch(n){if(!(n.code===`EPERM`||n.code===`EBUSY`||/EPERM|permission denied/i.test(String(n)))){b.debug(`Failed to remove directory`,{path:e,error:n instanceof Error?n.message:String(n),attempt:t});return}}let t=`${e}.orphaned.${Date.now()}`;try{c(e,t),b.debug(`Renamed locked directory to ${t} — deferred cleanup`);try{l(t,{recursive:!0,force:!0})}catch{}}catch(t){b.debug(`Failed to rename locked directory`,{path:e,error:t instanceof Error?t.message:String(t)})}}async function j(e){E(e);let n=`v${e}`,r=f(w,`${n}-staging`),i=f(w,n);try{A(r),o(r,{recursive:!0}),h(`tar -xzf "${h(`npm pack ${v}@${e} 2>${process.platform===`win32`?`NUL`:`/dev/null`}`,{cwd:r,encoding:`utf-8`,timeout:6e4,windowsHide:!0}).trim()}"`,{cwd:r,encoding:`utf-8`,stdio:`pipe`,timeout:3e4,windowsHide:!0});let n=f(r,`package`);h(`npm ${t.join(` `)}`,{cwd:n,encoding:`utf-8`,stdio:`pipe`,timeout:12e4,windowsHide:!0});let s=f(n,`packages`,`server`,`dist`,`bin.js`);if(!a(s))throw Error(`Server entry not found at ${s}`);if(!a(f(n,`node_modules`)))throw Error(`node_modules not found — npm install may have failed`);a(i)&&l(i,{recursive:!0,force:!0}),c(n,i);let d=`${C}.tmp`;u(d,JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)),c(d,C),N(e)}finally{A(r)}}function M(e){b.debug(`Updated to v${e}. Restarting server...`),setTimeout(()=>{process.exit(0)},300).unref()}function N(e){n(w,e??D())}async function P(){try{let e=s(C,`utf-8`),{version:t}=JSON.parse(e),n=await fetch(y,{signal:AbortSignal.timeout(1e4)});if(!n.ok)return;let r=(await n.json()).version;if(!r||r===t||!k(r,t))return;if(a(f(w,`v${r}`))){let e=`${C}.tmp`;u(e,JSON.stringify({version:r,installedAt:new Date().toISOString()},null,2)),c(e,C),b.debug(`Re-activated existing version v${r} — no download needed`),M(r);return}b.debug(`New version available: ${r}. Installing...`),await j(r),M(r)}catch(e){b.error(`Background update check failed: ${e instanceof Error?e.message:String(e)}`)}}let F=null;function I(){return F||(F=L().finally(()=>{F=null}),F)}async function L(){if(a(C)){await P();return}let e=D();try{let t=await fetch(y,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return;let n=(await t.json()).version;if(!n)return;if(O(e,n)<0){b.debug(`Newer version available — installing`,{currentVersion:e,latestVersion:n});try{await j(n),M(n)}catch(e){b.warn(`Auto-install failed`,{error:e instanceof Error?e.message:String(e),latestVersion:n})}}}catch{}}function R(){try{let e=p(_(),`.copilot`,`.aikit-scaffold.json`);return a(e)?JSON.parse(s(e,`utf-8`)).version??null:null}catch{return null}}function z(){try{let e=i();if(!e)return null;let t=p(e,`.github`,`.aikit-scaffold.json`);return a(t)?JSON.parse(s(t,`utf-8`)).version??null:null}catch{return null}}let B=`idle`,V=null,H=null,U=!1;function W(){return{state:B,error:V}}function G(){B=`idle`,V=null}function K(){try{let e=D();if(I(),!U){U=!0;try{let e=x();e&&g(process.execPath,[e,`migrate-launcher`],{cwd:_(),stdio:`ignore`,timeout:15e3,windowsHide:!0}).unref()}catch{}}let t=R(),n=z();if(!(t!=null&&t!==e)&&!(n!=null&&n!==e)||(H!==e&&(G(),H=e),B!==`idle`))return;B=`pending`,V=null,b.debug(`Scaffold version mismatch — auto-upgrading`,{serverVersion:e,userScaffoldVersion:t,workspaceScaffoldVersion:n});let r=x();if(!r){B=`failed`,V=`aikit CLI binary not found`,b.warn(`Cannot auto-upgrade: aikit CLI binary not found`);return}let i=_();m(process.execPath,[r,`upgrade`],{cwd:i,timeout:3e4,windowsHide:!0},(t,n,a)=>{t?(B=`failed`,V=t.message,b.warn(`Auto-upgrade failed`,{error:t.message,stack:t.stack,code:t.code,stdout:n?.slice(0,500),stderr:a?.slice(0,500),cwd:i,binPath:r,platform:process.platform})):(B=`success`,V=null,b.debug(`Auto-upgrade completed to version ${e}`))}).unref()}catch(e){B=`failed`,V=e instanceof Error?e.message:String(e),b.warn(`Auto-upgrade check failed`,{error:V})}}export{K as autoUpgradeScaffold,I as checkForUpdates,N as cleanupOldVersions,D as getCurrentVersion,W as getUpgradeState};
|