@gencode/agents 0.7.2 → 0.7.3
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/CHANGELOG.md +7 -0
- package/dist/builtin-provider-Bhzb_o53.js +66 -0
- package/dist/{goal-events-PYGTADzY.js → goal-events-Bdf1BDep.js} +1 -1
- package/dist/{goal-store-B36KsoVO.js → goal-store-DxaeZmiE.js} +1 -1
- package/dist/index.js +3 -3
- package/dist/{session-BDGOSbwC.js → session-CiekMEUQ.js} +2 -2
- package/dist/{session-store-CClsJSJO.js → session-store-DjXWnxJY.js} +1 -1
- package/package.json +1 -1
- package/dist/builtin-provider-CXE7L9HO.js +0 -66
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# @gencode/agents
|
|
2
2
|
|
|
3
|
+
## 0.7.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 0e4d28c: Require matching @custom-agent mentions to delegate through subagent_spawn with the exact agent name.
|
|
8
|
+
- 402af3c: Refactor SQLite database adaptation logic to be compatible with both Bun and Node.js runtimes
|
|
9
|
+
|
|
3
10
|
## 0.7.2
|
|
4
11
|
|
|
5
12
|
### Patch Changes
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{O as t,P as n,S as r}from"./session-CiekMEUQ.js";import{createRequire as i}from"node:module";import a from"node:fs/promises";import o,{basename as s}from"node:path";import c from"node:crypto";import l from"node:fs";function u(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}async function d(e){let t;try{t=await a.lstat(e)}catch(e){if(u(e))return{missing:!0};throw e}if(t.isSymbolicLink()||!t.isFile())throw Error(`path required`);return{missing:!1,stat:t}}function f(e){try{l.mkdirSync(e,{recursive:!0})}catch{}return e}function p(e){return e.trim().replace(/^[./]+/,``).replace(/\\/g,`/`)}function m(e){let t=p(e);return t?t===`MEMORY.md`||t===`memory.md`?!0:t.startsWith(`memory/`):!1}async function h(e,t){let n=await a.readdir(e,{withFileTypes:!0});for(let r of n){let n=o.join(e,r.name);if(!r.isSymbolicLink()){if(r.isDirectory()){await h(n,t);continue}r.isFile()&&r.name.endsWith(`.md`)&&t.push(n)}}}async function g(e){let t=[],n=o.join(e,`MEMORY.md`),r=o.join(e,`memory.md`),i=o.join(e,`memory`),s=async e=>{try{let n=await a.lstat(e);if(n.isSymbolicLink()||!n.isFile()||!e.endsWith(`.md`))return;t.push(e)}catch{}};await s(n),await s(r);try{let e=await a.lstat(i);!e.isSymbolicLink()&&e.isDirectory()&&await h(i,t)}catch{}if(t.length<=1)return t;let c=new Set,l=[];for(let e of t){let t=e;try{t=await a.realpath(e)}catch{}c.has(t)||(c.add(t),l.push(e))}return l}function _(e){return c.createHash(`sha256`).update(e).digest(`hex`)}async function ee(e,t){let n;try{n=await a.stat(e)}catch(e){if(u(e))return null;throw e}let r;try{r=await a.readFile(e,`utf-8`)}catch(e){if(u(e))return null;throw e}let i=_(r);return{path:o.relative(t,e).replace(/\\/g,`/`),absPath:e,mtimeMs:n.mtimeMs,size:n.size,hash:i}}function v(e,t){let n=e.split(`
|
|
2
|
+
`);if(n.length===0)return[];let r=Math.max(32,t.tokens*4),i=Math.max(0,t.overlap*4),a=[],o=[],s=0,c=()=>{if(o.length===0)return;let e=o[0],t=o[o.length-1];if(!e||!t)return;let n=o.map(e=>e.line).join(`
|
|
3
|
+
`),r=e.lineNo,i=t.lineNo;a.push({startLine:r,endLine:i,text:n,hash:_(n)})},l=()=>{if(i<=0||o.length===0){o=[],s=0;return}let e=0,t=[];for(let n=o.length-1;n>=0;--n){let r=o[n];if(r&&(e+=r.line.length+1,t.unshift(r),e>=i))break}o=t,s=t.reduce((e,t)=>e+t.line.length+1,0)};for(let e=0;e<n.length;e+=1){let t=n[e]??``,i=e+1,a=[];if(t.length===0)a.push(``);else for(let e=0;e<t.length;e+=r)a.push(t.slice(e,e+r));for(let e of a){let t=e.length+1;s+t>r&&o.length>0&&(c(),l()),o.push({line:e,lineNo:i}),s+=t}}return c(),a}function te(e,t){if(!(!t||t.length===0))for(let n of e)n.startLine=t[n.startLine-1]??n.startLine,n.endLine=t[n.endLine-1]??n.endLine}function y(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function ne(e,t){if(e.length===0||t.length===0)return 0;let n=Math.min(e.length,t.length),r=0,i=0,a=0;for(let o=0;o<n;o+=1){let n=e[o]??0,s=t[o]??0;r+=n*s,i+=n*n,a+=s*s}return i===0||a===0?0:r/(Math.sqrt(i)*Math.sqrt(a))}const b=i(import.meta.url);function x(){return globalThis.Bun!==void 0}function S(){try{return b(`node:sqlite`)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`SQLite support is unavailable in this Node runtime (missing node:sqlite). ${t}`,{cause:e})}}var re=class{constructor(e){this.stmt=e}all(...e){return this.stmt.all(...e)}get(...e){return this.stmt.get(...e)}run(...e){this.stmt.run(...e)}},ie=class{db;constructor(e,t){let n=b(`bun:sqlite`);this.db=new(n.Database??n.default?.Database)(e)}exec(e){console.log(`🚀 ~ BunDatabaseAdapter ~ exec ~ sql:`,e),this.db.run(e)}prepare(e){return console.log(`🚀 ~ BunDatabaseAdapter ~ prepare ~ sql:`,e),new re(this.db.prepare(e))}loadExtension(e){console.log(`🚀 ~ BunDatabaseAdapter ~ loadExtension ~ path:`,e),this.db.loadExtension(e)}close(){this.db.close()}},ae=class{stmt;constructor(e){this.stmt=e}all(...e){return this.stmt.all(...e)}get(...e){return this.stmt.get(...e)}run(...e){this.stmt.run(...e)}},oe=class{db;constructor(e,t){let{DatabaseSync:n}=S();this.db=new n(e,{allowExtension:t?.allowExtension})}exec(e){this.db.exec(e)}prepare(e){return new ae(this.db.prepare(e))}loadExtension(e){this.db.loadExtension(e)}close(){this.db.close()}};function se(e,t){return console.log(`🚀 ~ openDatabase ~ isBunRuntime():`,x()),x()?new ie(e,t):new oe(e,t)}function ce(e){return(e.toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[]).filter(Boolean)}function C(e){return c.createHash(`sha256`).update(e).digest().readUInt32BE(0)}function w(e,t=384){let n=Array(t).fill(0),r=ce(e);if(r.length===0)return n;for(let e of r){let r=C(e)%t;n[r]+=1}let i=Math.sqrt(n.reduce((e,t)=>e+t*t,0));if(i>0)for(let e=0;e<n.length;e+=1)n[e]=n[e]/i;return n}function T(e){let t=e?.model?.trim()||`mock-embedding-v1`,n=e?.dimensions??384;return{id:`external-mock`,model:t,embedQuery:async e=>w(e,n),embedBatch:async e=>e.map(e=>w(e,n))}}const E=new class{providers=new Map;byPluginId=new Map;register(e){this.providers.set(e.id,e),e.pluginId&&this.byPluginId.set(e.pluginId,e.id)}getById(e){return this.providers.get(e)}getByPluginId(e){let t=this.byPluginId.get(e);return t?this.providers.get(t):void 0}clear(){this.providers.clear(),this.byPluginId.clear()}};function le(e){let t=e.id?.trim()||e.pluginId;return E.register({id:t,pluginId:e.pluginId,create:e.create,config:e.config,rootDir:e.rootDir,source:e.source}),t}function D(e){let t=e.providerId?.trim(),n=e.pluginId?.trim(),r=(t?E.getById(t):void 0)??(n?E.getByPluginId(n):void 0);return r?{provider:r.create({dataDir:e.dataDir,memoryDir:e.memoryDir,pluginId:r.pluginId,config:r.config,rootDir:r.rootDir,source:r.source}),registration:r}:null}function ue(){E.clear()}const O={enabled:!1,lambda:.7};function k(e){let t=e.toLowerCase().match(/[a-z0-9_]+/g)??[];return new Set(t)}function de(e,t){if(e.size===0&&t.size===0)return 1;if(e.size===0||t.size===0)return 0;let n=0,r=e.size<=t.size?e:t,i=e.size<=t.size?t:e;for(let e of r)i.has(e)&&n++;let a=e.size+t.size-n;return a===0?0:n/a}function fe(e,t,n){if(t.length===0)return 0;let r=0,i=n.get(e.id)??k(e.content);for(let e of t){let t=de(i,n.get(e.id)??k(e.content));t>r&&(r=t)}return r}function A(e,t,n){return n*e-(1-n)*t}function j(e,t={}){let{enabled:n=O.enabled,lambda:r=O.lambda}=t;if(!n||e.length<=1)return[...e];let i=Math.max(0,Math.min(1,r));if(i===1)return e.slice().sort((e,t)=>t.score-e.score);let a=new Map;for(let t of e)a.set(t.id,k(t.content));let o=Math.max(...e.map(e=>e.score)),s=Math.min(...e.map(e=>e.score)),c=o-s,l=e=>c===0?1:(e-s)/c,u=[],d=new Set(e);for(;d.size>0;){let e=null,t=-1/0;for(let n of d){let r=A(l(n.score),fe(n,u,a),i);(r>t||r===t&&n.score>(e?.score??-1/0))&&(t=r,e=n)}if(e)u.push(e),d.delete(e);else break}return u}function M(e,t={}){if(e.length===0)return e;let n=new Map;return j(e.map((e,t)=>{let r=`${e.path}:${e.startLine}:${t}`;return n.set(r,e),{id:r,score:e.score,content:e.snippet}}),t).map(e=>n.get(e.id))}const N={enabled:!1,halfLifeDays:30},P=/(?:^|\/)(?:memory)\/(\d{4})-(\d{2})-(\d{2})\.md$/;function F(e){return!Number.isFinite(e)||e<=0?0:Math.LN2/e}function I(e){let t=F(e.halfLifeDays),n=Math.max(0,e.ageInDays);return t<=0||!Number.isFinite(n)?1:Math.exp(-t*n)}function L(e){return e.score*I(e)}function R(e){let t=e.replaceAll(`\\`,`/`).replace(/^\.\//,``),n=P.exec(t);if(!n)return null;let r=Number(n[1]),i=Number(n[2]),a=Number(n[3]);if(!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(a))return null;let o=Date.UTC(r,i-1,a),s=new Date(o);return s.getUTCFullYear()!==r||s.getUTCMonth()!==i-1||s.getUTCDate()!==a?null:s}function z(e){let t=e.replaceAll(`\\`,`/`).replace(/^\.\//,``);return t===`MEMORY.md`||t===`memory.md`?!0:t.startsWith(`memory/`)?!P.test(t):!1}async function B(e){let t=R(e.filePath);if(t)return t;if(e.source===`memory`&&z(e.filePath)||!e.memoryRoot)return null;let n=o.isAbsolute(e.filePath)?e.filePath:o.resolve(e.memoryRoot,e.filePath);try{let e=await a.stat(n);return Number.isFinite(e.mtimeMs)?new Date(e.mtimeMs):null}catch{return null}}function V(e,t){return Math.max(0,t-e.getTime())/864e5}async function pe(e){let t={...N,...e.temporalDecay};if(!t.enabled)return[...e.results];let n=e.nowMs??Date.now(),r=new Map;return Promise.all(e.results.map(async i=>{let a=`${i.source}:${i.path}`,o=r.get(a);o||(o=B({filePath:i.path,source:i.source,memoryRoot:e.memoryRoot}),r.set(a,o));let s=await o;if(!s)return i;let c=L({score:i.score,ageInDays:V(s,n),halfLifeDays:t.halfLifeDays});return{...i,score:c}}))}function me(e){let t=e.match(/[\p{L}\p{N}_]+/gu)?.map(e=>e.trim()).filter(Boolean)??[];return t.length===0?null:t.map(e=>`"${e.replaceAll(`"`,``)}"`).join(` AND `)}function he(e){return 1/(1+(Number.isFinite(e)?Math.max(0,e):999))}async function ge(e){let t=new Map;for(let n of e.vector)t.set(n.id,{id:n.id,path:n.path,startLine:n.startLine,endLine:n.endLine,source:n.source,snippet:n.snippet,vectorScore:n.vectorScore,textScore:0});for(let n of e.keyword){let e=t.get(n.id);e?(e.textScore=n.textScore,n.snippet&&n.snippet.length>0&&(e.snippet=n.snippet)):t.set(n.id,{id:n.id,path:n.path,startLine:n.startLine,endLine:n.endLine,source:n.source,snippet:n.snippet,vectorScore:0,textScore:n.textScore})}let n=(await pe({results:Array.from(t.values()).map(t=>{let n=e.vectorWeight*t.vectorScore+e.textWeight*t.textScore;return{path:t.path,startLine:t.startLine,endLine:t.endLine,score:n,snippet:t.snippet,source:t.source}}),temporalDecay:{...N,...e.temporalDecay},memoryRoot:e.memoryRoot,nowMs:e.nowMs})).slice().sort((e,t)=>t.score-e.score),r={...O,...e.mmr};return r.enabled?M(n,r):n}function _e(e){e.db.exec(`
|
|
4
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
5
|
+
key TEXT PRIMARY KEY,
|
|
6
|
+
value TEXT NOT NULL
|
|
7
|
+
);
|
|
8
|
+
`),e.db.exec(`
|
|
9
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
10
|
+
path TEXT PRIMARY KEY,
|
|
11
|
+
source TEXT NOT NULL DEFAULT 'memory',
|
|
12
|
+
hash TEXT NOT NULL,
|
|
13
|
+
mtime INTEGER NOT NULL,
|
|
14
|
+
size INTEGER NOT NULL
|
|
15
|
+
);
|
|
16
|
+
`),e.db.exec(`
|
|
17
|
+
CREATE TABLE IF NOT EXISTS chunks (
|
|
18
|
+
id TEXT PRIMARY KEY,
|
|
19
|
+
path TEXT NOT NULL,
|
|
20
|
+
source TEXT NOT NULL DEFAULT 'memory',
|
|
21
|
+
start_line INTEGER NOT NULL,
|
|
22
|
+
end_line INTEGER NOT NULL,
|
|
23
|
+
hash TEXT NOT NULL,
|
|
24
|
+
model TEXT NOT NULL,
|
|
25
|
+
text TEXT NOT NULL,
|
|
26
|
+
embedding TEXT NOT NULL,
|
|
27
|
+
updated_at INTEGER NOT NULL
|
|
28
|
+
);
|
|
29
|
+
`),e.db.exec(`
|
|
30
|
+
CREATE TABLE IF NOT EXISTS ${e.embeddingCacheTable} (
|
|
31
|
+
provider TEXT NOT NULL,
|
|
32
|
+
model TEXT NOT NULL,
|
|
33
|
+
provider_key TEXT NOT NULL,
|
|
34
|
+
hash TEXT NOT NULL,
|
|
35
|
+
embedding TEXT NOT NULL,
|
|
36
|
+
dims INTEGER,
|
|
37
|
+
updated_at INTEGER NOT NULL,
|
|
38
|
+
PRIMARY KEY (provider, model, provider_key, hash)
|
|
39
|
+
);
|
|
40
|
+
`),e.db.exec(`CREATE INDEX IF NOT EXISTS idx_embedding_cache_updated_at ON ${e.embeddingCacheTable}(updated_at);`);let t=!1,n;if(e.ftsEnabled)try{e.db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.ftsTable} USING fts5(\n text,\n id UNINDEXED,\n path UNINDEXED,\n source UNINDEXED,\n model UNINDEXED,\n start_line UNINDEXED,\n end_line UNINDEXED\n);`),t=!0}catch(e){let r=e instanceof Error?e.message:String(e);t=!1,n=r}return H(e.db,`files`,`source`,`TEXT NOT NULL DEFAULT 'memory'`),H(e.db,`chunks`,`source`,`TEXT NOT NULL DEFAULT 'memory'`),e.db.exec(`CREATE INDEX IF NOT EXISTS idx_chunks_path ON chunks(path);`),e.db.exec(`CREATE INDEX IF NOT EXISTS idx_chunks_source ON chunks(source);`),{ftsAvailable:t,...n?{ftsError:n}:{}}}function H(e,t,n,r){e.prepare(`PRAGMA table_info(${t})`).all().some(e=>e.name===n)||e.exec(`ALTER TABLE ${t} ADD COLUMN ${n} ${r}`)}function U(e,t){return e.length<=t?e:e.slice(0,t)}const ve=e=>Buffer.from(new Float32Array(e).buffer);async function ye(e){return e.queryVec.length===0||e.limit<=0?[]:await e.ensureVectorReady(e.queryVec.length)?e.db.prepare(`SELECT c.id, c.path, c.start_line, c.end_line, c.text,
|
|
41
|
+
c.source,
|
|
42
|
+
vec_distance_cosine(v.embedding, ?) AS dist
|
|
43
|
+
FROM ${e.vectorTable} v\n JOIN chunks c ON c.id = v.id\n WHERE c.model = ?${e.sourceFilterVec.sql}\n ORDER BY dist ASC\n LIMIT ?`).all(ve(e.queryVec),e.providerModel,...e.sourceFilterVec.params,e.limit).map(t=>({id:t.id,path:t.path,startLine:t.start_line,endLine:t.end_line,score:1-t.dist,snippet:U(t.text,e.snippetMaxChars),source:t.source})):be({db:e.db,providerModel:e.providerModel,sourceFilter:e.sourceFilterChunks}).map(t=>({chunk:t,score:ne(e.queryVec,t.embedding)})).filter(e=>Number.isFinite(e.score)).slice().sort((e,t)=>t.score-e.score).slice(0,e.limit).map(t=>({id:t.chunk.id,path:t.chunk.path,startLine:t.chunk.startLine,endLine:t.chunk.endLine,score:t.score,snippet:U(t.chunk.text,e.snippetMaxChars),source:t.chunk.source}))}function be(e){return e.db.prepare(`SELECT id, path, start_line, end_line, text, embedding, source
|
|
44
|
+
FROM chunks
|
|
45
|
+
WHERE model = ?${e.sourceFilter.sql}`).all(e.providerModel,...e.sourceFilter.params).map(e=>({id:e.id,path:e.path,startLine:e.start_line,endLine:e.end_line,text:e.text,embedding:y(e.embedding),source:e.source}))}async function xe(e){if(e.limit<=0)return[];let t=e.buildFtsQuery(e.query);if(!t)return[];let n=e.providerModel?` AND model = ?`:``,r=e.providerModel?[e.providerModel]:[];return e.db.prepare(`SELECT id, path, source, start_line, end_line, text,\n bm25(${e.ftsTable}) AS rank\n FROM ${e.ftsTable}\n WHERE ${e.ftsTable} MATCH ?${n}${e.sourceFilter.sql}\n ORDER BY rank ASC\n LIMIT ?`).all(t,...r,...e.sourceFilter.params,e.limit).map(t=>{let n=e.bm25RankToScore(t.rank);return{id:t.id,path:t.path,startLine:t.start_line,endLine:t.end_line,score:n,textScore:n,snippet:U(t.text,e.snippetMaxChars),source:t.source}})}const W={chunkTokens:400,chunkOverlap:80,maxResults:6,minScore:.2,fallback:{enabled:!0},embedding:{},experimental:{sessionMemory:!1},sources:[`memory`],store:{sessionStoreName:void 0,vector:{enabled:!0}},hybrid:{enabled:!0,vectorWeight:.7,textWeight:.3,candidateMultiplier:4,mmr:{enabled:!1,lambda:.7},temporalDecay:{enabled:!1,halfLifeDays:30}},cache:{enabled:!0,maxEntries:5e4},sync:{onSessionStart:!0,onSearch:!0,watch:!0,watchDebounceMs:1500,sessions:{deltaBytes:1e5,deltaMessages:50}},citations:`auto`};async function Se(e){try{let t=await import(`sqlite-vec`),n=(e.extensionPath?.trim()?e.extensionPath.trim():void 0)??t.getLoadablePath();return n?e.db.loadExtension(n):t.load(e.db),{ok:!0,extensionPath:n}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function Ce(e,n,r){let i=t(e,{storeName:r});return o.relative(i,n).replace(/\\/g,`/`)}async function we(e,n){let r=t(e,{storeName:n});try{let e=await a.readdir(r,{withFileTypes:!0}),t=[];for(let n of e){if(!n.isDirectory())continue;let e=o.join(r,n.name,`transcript.jsonl`);try{(await a.stat(e)).isFile()&&t.push(e)}catch{}}return t}catch(e){if(u(e))return[];throw e}}function Te(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e==`string`?e:e&&typeof e==`object`&&`text`in e?String(e.text??``):``).filter(Boolean).join(` `):e?String(e):``}async function Ee(e,t,i){let s;try{s=await a.stat(t)}catch(e){if(u(e))return null;throw e}let c;try{let e=await n(t);if(e===null)return null;c=e}catch(e){if(u(e))return null;throw e}let l=[],d=[],f=c.split(`
|
|
46
|
+
`);for(let e=0;e<f.length;e+=1){let t=f[e]?.trim();if(t)try{let n=JSON.parse(t),r=n.role??`unknown`,i=Te(n.content);if(!i)continue;let a=i.split(`
|
|
47
|
+
`);for(let t of a)l.push(`[${r}] ${t}`),d.push(e+1)}catch{}}let p=l.join(`
|
|
48
|
+
`),m=_(p);return{path:o.join(r(i),Ce(e,t,i)).replace(/\\/g,`/`),absPath:t,mtimeMs:s.mtimeMs,size:s.size,hash:m,content:p,lineMap:d}}const G=`chunks_vec`,K=`chunks_fts`,q=`embedding_cache`,J=`memory_index_meta_v1`,Y=3e4;function De(e,t,n){let r=t.split(`
|
|
49
|
+
`);for(let t of r){let n=t.match(/^##\s+(.+)$/);if(n?.[1])return`${e}#${n[1].trim()}`}return`${e}#L${n}`}const X=new Map;function Z(e,t){let n={...e,...t,hybrid:{...e.hybrid,...t?.hybrid??{}},cache:{...e.cache,...t?.cache??{}},sync:{...e.sync,...t?.sync??{}},experimental:{...e.experimental,...t?.experimental??{}},sources:t?.sources??e.sources,embedding:{...e.embedding,...t?.embedding??{}},store:{...e.store,...t?.store??{},vector:{...e.store.vector,...t?.store?.vector??{}}}};return n.experimental.sessionMemory&&!n.sources.includes(`sessions`)&&(n.sources=[...n.sources,`sessions`]),n}var Q=class e{dataDir;memoryRoot;storePath;config;sessionStoreName;provider;providerKey;embeddingProviderId;db;dirty=!0;ftsAvailable=!1;ftsError;vector={enabled:!0,available:null,extensionPath:void 0,loadError:void 0,dims:void 0};vectorReady=null;watchers=[];watchTimer=null;sessionWatchTimer=null;sessionsDirty=!1;sessionsDirtyFiles=new Set;sessionPendingFiles=new Set;searchFallbackOnly=!1;lastRebuildSummary;sessionDeltas=new Map;static get(t,n){let i=o.join(t,`.aimax`),a=Z(W,n),s=`${i}::${r(a.store.sessionStoreName)}`,c=X.get(s);if(c)return n&&c.applyConfig(n),c;let l=new e(t,i,a);return X.set(s,l),l}constructor(e,t,n){this.dataDir=e,this.memoryRoot=t,this.storePath=o.join(t,`.index.sqlite`),this.config=Z(W,n),this.sessionStoreName=r(this.config.store.sessionStoreName),this.provider=T(),this.providerKey=this.computeProviderKey(),this.applyEmbeddingProvider(),this.vector.enabled=this.config.store.vector.enabled,this.vector.extensionPath=this.config.store.vector.extensionPath,this.db=this.openDatabase(),this.ensureSchema(),this.ensureWatcher(),this.ensureSessionListener(),this.dirty=!0}applyConfig(e){this.config=Z(this.config,e),this.sessionStoreName=r(this.config.store.sessionStoreName),this.applyEmbeddingProvider(),this.vector.enabled=this.config.store.vector.enabled,this.vector.extensionPath=this.config.store.vector.extensionPath,this.ensureWatcher(),this.ensureSessionListener()}warmSession(){this.config.sync.onSessionStart&&this.sync({reason:`session-start`}).catch(()=>{})}noteSessionUpdate(e){this.scheduleSessionDirty(e)}status(){let e=this.buildSourceFilter(),t=this.db.prepare(`SELECT COUNT(*) as c FROM files WHERE 1=1${e.sql}`).get(...e.params),n=this.db.prepare(`SELECT COUNT(*) as c FROM chunks WHERE 1=1${e.sql}`).get(...e.params),r=(()=>{let t=Array.from(this.config.sources);if(t.length===0)return[];let n=new Map;for(let e of t)n.set(e,{files:0,chunks:0});let r=this.db.prepare(`SELECT source, COUNT(*) as c FROM files WHERE 1=1${e.sql} GROUP BY source`).all(...e.params);for(let e of r){let t=n.get(e.source)??{files:0,chunks:0};t.files=e.c??0,n.set(e.source,t)}let i=this.db.prepare(`SELECT source, COUNT(*) as c FROM chunks WHERE 1=1${e.sql} GROUP BY source`).all(...e.params);for(let e of i){let t=n.get(e.source)??{files:0,chunks:0};t.chunks=e.c??0,n.set(e.source,t)}return t.map(e=>Object.assign({source:e},n.get(e)))})(),i=this.provider?`hybrid`:`fts-only`,a=this.config.cache.enabled?this.db.prepare(`SELECT COUNT(*) as c FROM ${q}`).get()?.c??0:void 0;return{backend:`builtin`,files:t?.c??0,chunks:n?.c??0,dirty:this.dirty||this.sessionsDirty,workspaceDir:this.memoryRoot,dbPath:this.storePath,provider:this.provider.id,model:this.provider.model,sources:Array.from(this.config.sources),sourceCounts:r,cache:this.config.cache.enabled?{enabled:!0,entries:a,maxEntries:this.config.cache.maxEntries}:{enabled:!1,maxEntries:this.config.cache.maxEntries},fts:{enabled:this.config.hybrid.enabled,available:this.ftsAvailable,error:this.ftsError,rows:this.getFtsRowCount()},vector:{enabled:this.vector.enabled,available:this.vector.available??void 0,extensionPath:this.vector.extensionPath,loadError:this.vector.loadError,dims:this.vector.dims},custom:{searchMode:i,fallbackActive:this.searchFallbackOnly,lastRebuildSummary:this.lastRebuildSummary}}}async probeEmbeddingAvailability(){try{return await this.provider.embedBatch([`ping`]),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async probeVectorAvailability(){return this.vector.enabled?await this.ensureVectorReady():!1}async search(e){let t=e.trim();if(!t)return[];if(this.readMeta()?this.config.sync.onSearch&&(this.dirty||this.sessionsDirty)&&this.sync({reason:`search`}).catch(()=>{this.searchFallbackOnly=!0}):await this.sync({reason:`boot`}).catch(()=>{this.searchFallbackOnly=!0}),this.searchFallbackOnly)return this.decorateCitations(await this.fileScanSearch(t));let n=this.config.hybrid,r=Math.min(200,Math.max(1,Math.floor(this.config.maxResults*n.candidateMultiplier))),i=n.enabled&&this.ftsAvailable?await this.searchKeyword(t,r).catch(()=>[]):[],a=await this.provider.embedQuery(t).catch(()=>[]),o=a.some(e=>e!==0)?await this.searchVector(a,r).catch(()=>[]):[],s=[];if(!n.enabled||!this.ftsAvailable)s=o.filter(e=>e.score>=this.config.minScore).slice(0,this.config.maxResults);else{let e=await ge({vector:o.map(e=>({id:`${e.path}:${e.startLine}:${e.endLine}:${e.source}`,path:e.path,startLine:e.startLine,endLine:e.endLine,source:e.source,snippet:e.snippet,vectorScore:e.score})),keyword:i.map(e=>({id:`${e.path}:${e.startLine}:${e.endLine}:${e.source}`,path:e.path,startLine:e.startLine,endLine:e.endLine,source:e.source,snippet:e.snippet,textScore:e.textScore})),vectorWeight:n.vectorWeight,textWeight:n.textWeight,mmr:n.mmr,temporalDecay:n.temporalDecay,memoryRoot:this.memoryRoot}),t=e.filter(e=>e.score>=this.config.minScore);if(t.length>0||i.length===0)s=t.slice(0,this.config.maxResults);else{let t=Math.min(this.config.minScore,n.textWeight);s=e.filter(e=>e.score>=t).slice(0,this.config.maxResults)}}return s.length>0?this.decorateCitations(this.decorateEntryIds(s)):this.config.fallback.enabled?(this.searchFallbackOnly=!0,this.decorateCitations(this.decorateEntryIds(await this.fileScanSearch(t)))):[]}async readFile(e){let{absPath:t,relPath:n}=this.resolveMemoryFilePath(e.relPath);if((await d(t)).missing)return{text:``,path:n};let r;try{r=await a.readFile(t,`utf-8`)}catch(e){if(u(e))return{text:``,path:n};throw e}if(!e.from&&!e.lines)return{text:r,path:n};let i=r.split(`
|
|
50
|
+
`),o=Math.max(1,e.from??1),s=Math.max(1,e.lines??i.length);return{text:i.slice(o-1,o-1+s).join(`
|
|
51
|
+
`),path:n}}async replaceFile(e){let{absPath:t}=this.resolveMemoryFilePath(e.relPath);await a.mkdir(o.dirname(t),{recursive:!0}),await a.writeFile(t,e.content,`utf-8`),this.dirty=!0,await this.syncAndPostCheck(`replace`)}async deleteFile(e){let{absPath:t}=this.resolveMemoryFilePath(e);try{await a.unlink(t)}catch(e){if(u(e))return;throw e}this.dirty=!0,await this.syncAndPostCheck(`delete`)}async appendToMemory(e){let t=this.memoryRoot;await a.mkdir(t,{recursive:!0});let n=o.join(t,`MEMORY.md`),r=e.endsWith(`
|
|
52
|
+
`)?e:`${e}\n`;await a.appendFile(n,r,`utf-8`),this.dirty=!0,await this.syncAndPostCheck(`append`)}openDatabase(){return f(o.dirname(this.storePath)),se(this.storePath,{allowExtension:this.vector.enabled})}ensureSchema(){let e=_e({db:this.db,embeddingCacheTable:q,ftsTable:K,ftsEnabled:this.config.hybrid.enabled});this.ftsAvailable=e.ftsAvailable,e.ftsError&&(this.ftsError=e.ftsError)}async ensureVectorReady(e){if(!this.vector.enabled)return!1;this.vectorReady||=this.withTimeout(this.loadVectorExtension(),Y,`sqlite-vec load timed out after ${Math.round(Y/1e3)}s`);let t=!1;try{t=await this.vectorReady||!1}catch(e){let t=e instanceof Error?e.message:String(e);return this.vector.available=!1,this.vector.loadError=t,this.vectorReady=null,!1}return t&&typeof e==`number`&&e>0&&this.ensureVectorTable(e),t}async loadVectorExtension(){if(this.vector.available!==null)return this.vector.available;if(!this.vector.enabled)return this.vector.available=!1,!1;try{let e=this.vector.extensionPath?.trim()?this.vector.extensionPath.trim():void 0,t=await Se({db:this.db,extensionPath:e});if(!t.ok)throw Error(t.error??`unknown sqlite-vec load error`);return this.vector.extensionPath=t.extensionPath,this.vector.available=!0,!0}catch(e){let t=e instanceof Error?e.message:String(e);return this.vector.available=!1,this.vector.loadError=t,!1}}ensureVectorTable(e){this.vector.dims!==e&&(this.vector.dims&&this.vector.dims!==e&&this.dropVectorTable(),this.db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${G} USING vec0(\n id TEXT PRIMARY KEY,\n embedding FLOAT[${e}]\n)`),this.vector.dims=e)}dropVectorTable(){try{this.db.exec(`DROP TABLE IF EXISTS ${G}`)}catch{}}async withTimeout(e,t,n){if(!Number.isFinite(t)||t<=0)return await e;let r=null,i=new Promise((e,i)=>{r=setTimeout(()=>i(Error(n)),t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}ensureWatcher(){if(!this.config.sync.watch||this.watchers.length>0)return;let e=[o.join(this.memoryRoot,`MEMORY.md`),o.join(this.memoryRoot,`memory.md`),o.join(this.memoryRoot,`memory`)],t=()=>{this.dirty=!0,this.scheduleWatchSync()};for(let n of e)try{let e=l.watch(n,{recursive:!1},t);e.on(`error`,()=>{try{e.close()}catch{}}),this.watchers.push(e)}catch{}}scheduleWatchSync(){this.config.sync.watch&&(this.watchTimer&&clearTimeout(this.watchTimer),this.watchTimer=setTimeout(()=>{this.watchTimer=null,this.sync({reason:`watch`}).catch(()=>{})},this.config.sync.watchDebounceMs))}ensureSessionListener(){if(!this.config.experimental.sessionMemory)return;let e=t(this.dataDir,{storeName:this.sessionStoreName});try{let t=l.watch(e,{recursive:!0},(t,n)=>{if(!n||!n.endsWith(`transcript.jsonl`))return;let r=o.join(e,n);this.scheduleSessionDirty(r)});this.watchers.push(t)}catch{}}scheduleSessionDirty(e){this.config.experimental.sessionMemory&&(this.sessionPendingFiles.add(e),!this.sessionWatchTimer&&(this.sessionWatchTimer=setTimeout(()=>{this.sessionWatchTimer=null,this.processSessionDeltaBatch().catch(()=>{})},5e3)))}async processSessionDeltaBatch(){if(this.sessionPendingFiles.size===0)return;let e=Array.from(this.sessionPendingFiles);this.sessionPendingFiles.clear();let t=!1;for(let n of e){let e=await this.updateSessionDelta(n);if(!e)continue;let r=e.deltaBytes,i=e.deltaMessages,a=r<=0?e.pendingBytes>0:e.pendingBytes>=r,o=i<=0?e.pendingMessages>0:e.pendingMessages>=i;!a&&!o||(this.sessionsDirtyFiles.add(n),this.sessionsDirty=!0,e.pendingBytes=r>0?Math.max(0,e.pendingBytes-r):0,e.pendingMessages=i>0?Math.max(0,e.pendingMessages-i):0,t=!0)}t&&this.sync({reason:`session-delta`}).catch(()=>{})}async updateSessionDelta(e){let t=this.config.sync.sessions;if(!t)return null;let n;try{n=await a.stat(e)}catch{return null}let r=n.size,i=this.sessionDeltas.get(e);i||(i={lastSize:0,pendingBytes:0,pendingMessages:0},this.sessionDeltas.set(e,i));let o=Math.max(0,r-i.lastSize);return o===0&&r===i.lastSize?{deltaBytes:t.deltaBytes,deltaMessages:t.deltaMessages,pendingBytes:i.pendingBytes,pendingMessages:i.pendingMessages}:(r<i.lastSize?(i.lastSize=r,i.pendingBytes+=r,t.deltaMessages>0&&(t.deltaBytes<=0||i.pendingBytes<t.deltaBytes)&&(i.pendingMessages+=await this.countNewlines(e,0,r))):(i.pendingBytes+=o,t.deltaMessages>0&&(t.deltaBytes<=0||i.pendingBytes<t.deltaBytes)&&(i.pendingMessages+=await this.countNewlines(e,i.lastSize,r)),i.lastSize=r),this.sessionDeltas.set(e,i),{deltaBytes:t.deltaBytes,deltaMessages:t.deltaMessages,pendingBytes:i.pendingBytes,pendingMessages:i.pendingMessages})}async countNewlines(e,t,n){if(n<=t)return 0;let r;try{r=await a.open(e,`r`)}catch{return 0}try{let e=t,i=0,a=Buffer.alloc(64*1024);for(;e<n;){let t=Math.min(a.length,n-e),{bytesRead:o}=await r.read(a,0,t,e);if(o<=0)break;for(let e=0;e<o;e+=1)a[e]===10&&(i+=1);e+=o}return i}finally{await r.close()}}computeProviderKey(){return _(JSON.stringify({provider:this.provider.id,model:this.provider.model}))}resolveMemoryFilePath(e){let t=e.trim();if(!t)throw Error(`path required`);let n=o.isAbsolute(t)?o.resolve(t):o.resolve(this.memoryRoot,t),r=o.relative(this.memoryRoot,n).replace(/\\/g,`/`);if(!(r.length>0&&!r.startsWith(`..`)&&!o.isAbsolute(r)&&m(r))||!n.endsWith(`.md`))throw Error(`path required`);return{absPath:n,relPath:r}}applyEmbeddingProvider(){let e=this.config.embedding?.providerId?.trim();if(e){let t=D({providerId:e,dataDir:this.dataDir,memoryDir:this.memoryRoot});if(!t)throw Error(`Embedding provider not found: ${e}`);this.provider=t.provider,this.embeddingProviderId=e,this.providerKey=this.computeProviderKey(),this.dirty=!0;return}this.embeddingProviderId&&(this.provider=T(),this.embeddingProviderId=void 0,this.providerKey=this.computeProviderKey(),this.dirty=!0)}readMeta(){let e=this.db.prepare(`SELECT value FROM meta WHERE key = ?`).get(J);if(!e?.value)return null;try{return JSON.parse(e.value)}catch{return null}}writeMeta(e){let t=JSON.stringify(e);this.db.prepare(`INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`).run(J,t)}loadEmbeddingCache(e){if(!this.config.cache.enabled||e.length===0)return new Map;let t=Array.from(new Set(e.filter(Boolean)));if(t.length===0)return new Map;let n=new Map,r=[this.provider.id,this.provider.model,this.providerKey];for(let e=0;e<t.length;e+=400){let i=t.slice(e,e+400),a=i.map(()=>`?`).join(`, `),o=this.db.prepare(`SELECT hash, embedding FROM ${q}\n WHERE provider = ? AND model = ? AND provider_key = ? AND hash IN (${a})`).all(...r,...i);for(let e of o)n.set(e.hash,y(e.embedding))}return n}upsertEmbeddingCache(e){if(!this.config.cache.enabled||e.length===0)return;let t=Date.now(),n=this.db.prepare(`INSERT INTO ${q} (provider, model, provider_key, hash, embedding, dims, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(provider, model, provider_key, hash) DO UPDATE SET\n embedding=excluded.embedding,\n dims=excluded.dims,\n updated_at=excluded.updated_at`);for(let r of e){let e=r.embedding??[];n.run(this.provider.id,this.provider.model,this.providerKey,r.hash,JSON.stringify(e),e.length,t)}}async embedChunks(e){if(e.length===0)return[];let t=this.loadEmbeddingCache(e.map(e=>e.hash)),n=Array.from({length:e.length},()=>[]),r=[];for(let i=0;i<e.length;i+=1){let a=e[i],o=a?.hash?t.get(a.hash):void 0;o&&o.length>0?n[i]=o:a&&r.push({index:i,chunk:a})}if(r.length===0)return n;let i=await this.provider.embedBatch(r.map(e=>e.chunk.text)),a=[];for(let e=0;e<r.length;e+=1){let t=r[e],o=i[e]??[];n[t.index]=o,a.push({hash:t.chunk.hash,embedding:o})}return this.upsertEmbeddingCache(a),n}async indexFile(e,t){let n=v(t.content??await a.readFile(e.absPath,`utf-8`),{tokens:this.config.chunkTokens,overlap:this.config.chunkOverlap}).filter(e=>e.text.trim().length>0);t.source===`sessions`&&te(n,t.lineMap);let r=await this.embedChunks(n),i=r.find(e=>e.length>0),o=i?await this.ensureVectorReady(i.length):!1,s=Date.now();if(o)try{this.db.prepare(`DELETE FROM ${G} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(e.path,t.source)}catch{}if(this.ftsAvailable)try{this.db.prepare(`DELETE FROM ${K} WHERE path = ? AND source = ? AND model = ?`).run(e.path,t.source,this.provider.model)}catch{}this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(e.path,t.source);for(let i=0;i<n.length;i+=1){let a=n[i],c=r[i]??[],l=_(`${t.source}:${e.path}:${a.startLine}:${a.endLine}:${a.hash}:${this.provider.model}`);if(this.db.prepare(`INSERT INTO chunks (id, path, source, start_line, end_line, hash, model, text, embedding, updated_at)
|
|
53
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
54
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
55
|
+
hash=excluded.hash,
|
|
56
|
+
model=excluded.model,
|
|
57
|
+
text=excluded.text,
|
|
58
|
+
embedding=excluded.embedding,
|
|
59
|
+
updated_at=excluded.updated_at`).run(l,e.path,t.source,a.startLine,a.endLine,a.hash,this.provider.model,a.text,JSON.stringify(c),s),o&&c.length>0){try{this.db.prepare(`DELETE FROM ${G} WHERE id = ?`).run(l)}catch{}this.db.prepare(`INSERT INTO ${G} (id, embedding) VALUES (?, ?)`).run(l,Buffer.from(new Float32Array(c).buffer))}this.ftsAvailable&&this.db.prepare(`INSERT INTO ${K} (text, id, path, source, model, start_line, end_line)\n VALUES (?, ?, ?, ?, ?, ?, ?)`).run(a.text,l,e.path,t.source,this.provider.model,a.startLine,a.endLine)}this.db.prepare(`INSERT INTO files (path, source, hash, mtime, size) VALUES (?, ?, ?, ?, ?)
|
|
60
|
+
ON CONFLICT(path) DO UPDATE SET
|
|
61
|
+
source=excluded.source,
|
|
62
|
+
hash=excluded.hash,
|
|
63
|
+
mtime=excluded.mtime,
|
|
64
|
+
size=excluded.size`).run(e.path,t.source,e.hash,e.mtimeMs,e.size)}buildSourceFilter(){let e=this.config.sources;return e.length?{sql:` AND source IN (${e.map(()=>`?`).join(`, `)})`,params:e}:{sql:``,params:[]}}async searchVector(e,t){return await ye({db:this.db,vectorTable:G,providerModel:this.provider.model,queryVec:e,limit:t,snippetMaxChars:700,ensureVectorReady:async e=>await this.ensureVectorReady(e),sourceFilterVec:this.buildSourceFilter(),sourceFilterChunks:this.buildSourceFilter()})}async searchKeyword(e,t){return this.ftsAvailable?await xe({db:this.db,ftsTable:K,providerModel:this.provider.model,query:e,limit:t,snippetMaxChars:700,sourceFilter:this.buildSourceFilter(),buildFtsQuery:e=>me(e),bm25RankToScore:he}):[]}resetIndex(){if(this.db.exec(`DELETE FROM files`),this.db.exec(`DELETE FROM chunks`),this.ftsAvailable)try{this.db.exec(`DELETE FROM ${K}`)}catch{}this.dropVectorTable(),this.vector.dims=void 0,this.sessionsDirtyFiles.clear()}async syncAndPostCheck(e){try{await this.sync({reason:`mutation-postcheck`})}catch{this.searchFallbackOnly=!0;return}this.searchFallbackOnly=!this.indexHasSearchableData()}indexHasSearchableData(){try{if((this.db.prepare(`SELECT COUNT(*) as c FROM chunks`).get()?.c??0)>0)return!0}catch{}try{if(l.readdirSync(this.memoryRoot).filter(e=>e.endsWith(`.md`)).length>0)return!1;let e=o.join(this.memoryRoot,`memory`);return l.existsSync(e)?l.readdirSync(e).filter(e=>e.endsWith(`.md`)).length===0:!0}catch{return!1}}async fileScanSearch(e){let t=e.trim().toLowerCase();if(!t)return[];let n=await g(this.memoryRoot),r=[];for(let e of n){let n=``;try{n=await a.readFile(e,`utf-8`)}catch{continue}let i=o.relative(this.memoryRoot,e).replace(/\\/g,`/`);i.startsWith(`memory/`);let c=n.split(`
|
|
65
|
+
`);for(let n=0;n<c.length;n+=1){let a=c[n]??``,o=a.toLowerCase();if(!o.includes(t))continue;let l=o===t?1:Math.max(.2,t.length/Math.max(a.length,t.length));r.push({path:i||s(e),startLine:n+1,endLine:n+1,score:Number(l.toFixed(4)),snippet:a.slice(0,700),source:`memory`})}}return r.sort((e,t)=>t.score-e.score||e.path.localeCompare(t.path)||e.startLine-t.startLine),r.slice(0,this.config.maxResults)}getFtsRowCount(){if(this.ftsAvailable)try{return this.db.prepare(`SELECT COUNT(*) as c FROM ${K}`).get()?.c??0}catch{return}}buildRebuildSummary(e){let t=this.db.prepare(`SELECT COUNT(*) as c FROM chunks`).get();return{reason:e.reason,memoryFilesIndexed:e.memoryFilesIndexed,sessionFilesIndexed:e.sessionFilesIndexed,staleMemoryFilesRemoved:e.staleMemoryFilesRemoved,staleSessionFilesRemoved:e.staleSessionFilesRemoved,chunks:t?.c??0,ftsRows:this.getFtsRowCount(),fallbackActive:this.searchFallbackOnly,needsFullReindex:e.needsFullReindex}}async rebuild(e=`manual-rebuild`){return this.resetIndex(),this.dirty=!0,this.sessionsDirty=!0,await this.sync({reason:e,forceFullReindex:!0}),this.lastRebuildSummary??this.buildRebuildSummary({reason:e,memoryFilesIndexed:0,sessionFilesIndexed:0,staleMemoryFilesRemoved:0,staleSessionFilesRemoved:0,needsFullReindex:!0})}async sync(e){let t=this.readMeta(),n=e?.forceFullReindex||!t||t.model!==this.provider.model||t.provider!==this.provider.id||t.providerKey!==this.providerKey||t.chunkTokens!==this.config.chunkTokens||t.chunkOverlap!==this.config.chunkOverlap||this.vector.available&&!t?.vectorDims;n&&this.resetIndex();let r=await g(this.memoryRoot),i=(await Promise.all(r.map(async e=>ee(e,this.memoryRoot)))).filter(e=>e!==null),a=new Set(i.map(e=>e.path)),o=0,s=i.map(e=>async()=>{let t=this.db.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`).get(e.path,`memory`);!n&&t?.hash===e.hash||(await this.indexFile(e,{source:`memory`}),o+=1)});for(let e of s)await e();let c=0,l=this.db.prepare(`SELECT path FROM files WHERE source = ?`).all(`memory`);for(let e of l)if(!a.has(e.path)){this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(e.path,`memory`),c+=1;try{this.db.prepare(`DELETE FROM ${G} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(e.path,`memory`)}catch{}if(this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(e.path,`memory`),this.ftsAvailable)try{this.db.prepare(`DELETE FROM ${K} WHERE path = ? AND source = ? AND model = ?`).run(e.path,`memory`,this.provider.model)}catch{}}let u={indexed:0,staleRemoved:0};this.config.experimental.sessionMemory&&(n||this.sessionsDirty)&&(u=await this.syncSessionFiles(n)),this.writeMeta({model:this.provider.model,provider:this.provider.id,providerKey:this.providerKey,chunkTokens:this.config.chunkTokens,chunkOverlap:this.config.chunkOverlap,...this.vector.available&&this.vector.dims?{vectorDims:this.vector.dims}:{}}),this.dirty=!1,this.searchFallbackOnly=!this.indexHasSearchableData(),this.lastRebuildSummary=this.buildRebuildSummary({reason:e?.reason??`sync`,memoryFilesIndexed:o,sessionFilesIndexed:u.indexed,staleMemoryFilesRemoved:c,staleSessionFilesRemoved:u.staleRemoved,needsFullReindex:!!n})}async syncSessionFiles(e){let t=await we(this.dataDir,this.sessionStoreName),n=(await Promise.all(t.map(async e=>Ee(this.dataDir,e,this.sessionStoreName)))).filter(e=>e!==null),r=new Set(n.map(e=>e.path)),i=e||this.sessionsDirtyFiles.size===0,a=0;for(let t of n){if(!i&&!this.sessionsDirtyFiles.has(t.absPath))continue;let n=this.db.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`).get(t.path,`sessions`);if(!e&&n?.hash===t.hash){this.resetSessionDelta(t.absPath,t.size);continue}await this.indexFile(t,{source:`sessions`,content:t.content,lineMap:t.lineMap}),a+=1,this.resetSessionDelta(t.absPath,t.size)}let o=0,s=this.db.prepare(`SELECT path FROM files WHERE source = ?`).all(`sessions`);for(let e of s)if(!r.has(e.path)){this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(e.path,`sessions`),o+=1;try{this.db.prepare(`DELETE FROM ${G} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(e.path,`sessions`)}catch{}if(this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(e.path,`sessions`),this.ftsAvailable)try{this.db.prepare(`DELETE FROM ${K} WHERE path = ? AND source = ? AND model = ?`).run(e.path,`sessions`,this.provider.model)}catch{}}return this.sessionsDirty=!1,this.sessionsDirtyFiles.clear(),{indexed:a,staleRemoved:o}}resetSessionDelta(e,t){let n=this.sessionDeltas.get(e);n&&(n.lastSize=t,n.pendingBytes=0,n.pendingMessages=0)}decorateCitations(e){return this.config.citations===`off`?e:e.map(e=>{let t=`Source: ${e.path}#L${e.startLine}-L${e.endLine}`;return this.config.citations===`on`?{...e,citation:t,snippet:`${e.snippet}\n\n${t}`}:{...e,citation:t}})}decorateEntryIds(e){return e.map(e=>{if(e.id)return e;let t=De(e.path,e.snippet,e.startLine);return{...e,id:t}})}},Oe=e({createBuiltinMemoryProvider:()=>$});function $(e,t){let n=Q.get(e.dataDir,t?.includeSessions?{experimental:{sessionMemory:!0},sources:[`memory`,`sessions`],store:{sessionStoreName:e.sessionStoreName,vector:{enabled:!0}}}:e.sessionStoreName?{store:{sessionStoreName:e.sessionStoreName,vector:{enabled:!0}}}:void 0),r=e.memoryDir;return{id:`builtin-memory`,name:`Builtin Memory Provider`,status:()=>n.status(),search:async(e,t)=>n.search(e),getLines:async(e,t,r)=>{let i=Math.max(1,r-t+1),a=await n.readFile({relPath:e,from:t,lines:i});return a.text?a.text.split(`
|
|
66
|
+
`):[]},listFiles:async()=>g(r),append:async e=>n.appendToMemory(e),updateFile:async(e,t)=>{await n.replaceFile({relPath:e,content:t})},deleteFile:async e=>{await n.deleteFile(e)},sync:async e=>{if(e===`cli-rebuild`){await n.rebuild(e);return}await n.sync({reason:e??`provider-sync`})},noteSessionUpdate:e=>{let t=o.isAbsolute(e)?e:o.resolve(e);n.noteSessionUpdate(t)}}}export{ue as a,le as i,$ as n,D as o,Q as r,g as s,Oe as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{T as t}from"./session-
|
|
1
|
+
import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{T as t}from"./session-CiekMEUQ.js";import n from"node:fs/promises";import r from"node:path";var i=e({appendGoalEvent:()=>o,goalEventsPath:()=>a});function a(e,n,i){return r.join(t(e,n,i),`goal-events.jsonl`)}async function o(e,t,i,o){let s={...i,sessionId:t,timestamp:new Date().toISOString()},c=a(e,t,o);await n.mkdir(r.dirname(c),{recursive:!0}),await n.appendFile(c,`${JSON.stringify(s)}\n`,`utf-8`)}export{a as n,i as r,o as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{T as t,j as n}from"./session-
|
|
1
|
+
import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{T as t,j as n}from"./session-CiekMEUQ.js";import{t as r}from"./goal-events-Bdf1BDep.js";import{MAX_GOAL_OBJECTIVE_CHARS as i}from"@gencode/shared";import a from"node:fs/promises";import o from"node:path";import{randomUUID as s}from"node:crypto";var c=e({GoalObjectiveResolutionError:()=>l,deleteGoal:()=>g,goalObjectiveMdPath:()=>d,goalPath:()=>u,mirrorGoalStatusToSession:()=>_,readGoal:()=>f,resolveGoalObjective:()=>p,updateGoal:()=>h,writeGoal:()=>m}),l=class extends Error{constructor(e,t){super(e,t),this.name=`GoalObjectiveResolutionError`}};function u(e,n,r){return o.join(t(e,n,r),`goal.json`)}function d(e,n,r){return o.join(t(e,n,r),`goal-objective.md`)}async function f(e,t,n){let r=u(e,t,n);try{let e=await a.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function p(e,n,r,i){if(r.objectiveRef){let s=o.join(t(e,n,i),r.objectiveRef);try{return await a.readFile(s,`utf-8`)}catch(e){throw new l(`Goal objective reference "${r.objectiveRef}" could not be read for session "${n}"`,{cause:e})}}return r.objective}async function m(e,n,o,c){let l=await f(e,n,c),m=o.objective.trim(),h=new Date().toISOString(),g={...o,objective:m,goalId:o.goalId??s(),createdAt:o.createdAt??h,updatedAt:o.updatedAt??h};l&&((await p(e,n,l,c)).trim()===m?l.pendingObjectiveUpdatedNotice&&(g.pendingObjectiveUpdatedNotice=!0):g.pendingObjectiveUpdatedNotice=!0);let v=t(e,n,c);await a.mkdir(v,{recursive:!0});let y;if(g.objective.length>i)y=g.objective,g.objective=g.objective.slice(0,200)+`...`,g.objectiveRef=`goal-objective.md`;else{delete g.objectiveRef;try{await a.unlink(d(e,n,c))}catch(e){if(e.code!==`ENOENT`)throw e}}if(y!==void 0){let t=d(e,n,c),r=t+`.tmp`;await a.writeFile(r,y,`utf-8`),await a.rename(r,t)}let b=u(e,n,c),x=b+`.tmp`;return await a.writeFile(x,JSON.stringify(g,null,2),`utf-8`),await a.rename(x,b),await _(e,n,g.status,c),await r(e,n,{goalId:g.goalId,action:l?`replaced`:`created`,status:g.status,source:c?.eventSource??`store`,detail:l?{previousGoalId:l.goalId}:void 0},c),g}async function h(e,t,n,i){let o=await f(e,t,i);if(!o)return null;if(`objective`in n||`objectiveRef`in n||`goalId`in n||`createdAt`in n)throw Error(`updateGoal only supports status, tokenBudget, tokensUsed, and timeUsedSeconds; use writeGoal() to change the objective`);let s={...o,...n,updatedAt:new Date().toISOString()},c=u(e,t,i),l=c+`.tmp`;await a.writeFile(l,JSON.stringify(s,null,2),`utf-8`),await a.rename(l,c),n.status!==void 0&&await _(e,t,s.status,i);let d=n.status===`paused`?`paused`:n.status===`active`&&o.status!==`active`?`resumed`:n.status===`budget_limited`?`budget_limited`:n.status===`complete`?`completed`:`updated`;return await r(e,t,{goalId:s.goalId,action:d,status:s.status,source:i?.eventSource??`store`,detail:{fields:Object.keys(n)}},i),s}async function g(e,t,n){let i=await f(e,t,n),o=u(e,t,n),s=!1;try{await a.unlink(o),s=!0}catch(e){if(e.code!==`ENOENT`)throw e}let c=d(e,t,n);try{await a.unlink(c)}catch{}return s&&(await _(e,t,null,n),await r(e,t,{goalId:i?.goalId??null,action:`deleted`,status:null,source:n?.eventSource??`store`},n)),s}async function _(e,t,r,i){await n(e,t,{goalStatus:r},i)}export{_ as a,h as c,c as i,m as l,d as n,f as o,u as r,p as s,g as t};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as e,C as t,D as n,E as r,F as i,I as a,M as o,N as s,O as c,P as l,S as u,T as d,_ as f,a as p,b as m,c as h,d as g,f as _,g as v,h as y,i as b,j as x,k as S,l as C,m as w,n as T,o as E,p as D,r as O,s as k,t as ee,u as A,v as j,w as te,x as M,y as N}from"./session-
|
|
1
|
+
import{A as e,C as t,D as n,E as r,F as i,I as a,M as o,N as s,O as c,P as l,S as u,T as d,_ as f,a as p,b as m,c as h,d as g,f as _,g as v,h as y,i as b,j as x,k as S,l as C,m as w,n as T,o as E,p as D,r as O,s as k,t as ee,u as A,v as j,w as te,x as M,y as N}from"./session-CiekMEUQ.js";import{n as P,t as F}from"./goal-events-Bdf1BDep.js";import{a as I,c as L,l as R,n as z,o as B,r as V,s as H,t as U}from"./goal-store-DxaeZmiE.js";import{a as ne,i as W,n as re,o as ie,r as ae,s as oe}from"./builtin-provider-Bhzb_o53.js";import{i as se,n as ce,r as le}from"./provider-registry-Kh5nNG84.js";import{a as ue,i as de,l as fe,n as pe,o as me,r as he,s as ge,t as _e}from"./session-store-DjXWnxJY.js";import{_ as ve,a as ye,c as be,d as xe,f as Se,g as Ce,h as we,i as Te,l as Ee,m as De,n as Oe,o as ke,p as Ae,s as je,t as Me,u as Ne,v as Pe}from"./config-CJ7qy-pr.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Fe,formatTaskForDisplay as Ie,isHitlExpired as Le,isHitlTool as Re,validateUiToolResult as ze}from"@gencode/shared";import G,{readFile as Be}from"node:fs/promises";import K,{join as Ve}from"node:path";import He from"gray-matter";import{createHash as Ue,randomUUID as We}from"node:crypto";import{TextDecoder as Ge}from"node:util";import{Agent as Ke}from"@mariozechner/pi-agent-core";import{AsyncLocalStorage as qe}from"node:async_hooks";import Je from"openai";import{Type as q,calculateCost as Ye,getEnvApiKey as Xe,parseStreamingJson as Ze,registerApiProvider as Qe,registerBuiltInApiProviders as $e,supportsXhigh as et}from"@mariozechner/pi-ai";import{AssistantMessageEventStream as tt}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as nt}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as rt,hasCopilotVisionInput as it}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as at,clampReasoning as ot}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as st}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import J from"node:fs";import ct from"log4js";import lt from"node:os";import{spawn as ut}from"node:child_process";import{isBinaryFile as dt}from"isbinaryfile";import ft from"ajv";import{createJiti as pt}from"jiti";const mt=2e4,ht=15e4,gt=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function _t(e){return K.join(e,`.aimax`)}async function vt(e){let t=_t(e),n=[];for(let e of gt){let r=K.join(t,e);try{let t=await G.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await G.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function yt(e,t,n){let r=e.trimEnd();if(r.length<=n)return{result:r,truncated:!1,originalLength:r.length};let i=Math.floor(n*.7),a=Math.floor(n*.2),o=r.slice(0,i),s=r.slice(-a);return{result:[o,[``,`[...truncated, read ${t} for full content...]`,`…(truncated ${t}: kept ${i}+${a} chars of ${r.length})…`,``].join(`
|
|
2
2
|
`),s].join(`
|
|
3
3
|
`),truncated:!0,originalLength:r.length}}function bt(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function xt(e,t){let n=t?.maxChars??mt,r=Math.max(1,t?.totalMaxChars??Math.max(n,ht)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=bt(`[MISSING] Expected at: ${a.path}`,r);if(!e)break;r=Math.max(0,r-e.length),i.push({path:a.path,content:e});continue}if(r<64){t?.warn?.(`remaining bootstrap budget is ${r} chars (<64); skipping additional files`);break}let e=Math.max(1,Math.min(n,r)),{result:o,truncated:s,originalLength:c}=yt(a.content??``,a.name,e),l=bt(o,r);l&&((s||l.length<o.length)&&t?.warn?.(`bootstrap file ${a.name} is ${c} chars (limit ${e}); truncating`),r=Math.max(0,r-l.length),i.push({path:a.path,content:l}))}return i}const St=`You are a personal assistant running inside AiMax.`;async function Ct(e){try{return{presetSystemPrompt:He(await G.readFile(e,`utf-8`)).content.trim()||St}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:St};throw e}}async function wt(){return Ct(`/aimax/system_prompt.md`)}function Tt(e){return K.join(e,`.aimax`,`skills`)}function Et(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Dt(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${Et(n)}\n`)}function Ot(e){let t=He(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
|
|
4
4
|
`);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}async function kt(e){return jt([Tt(e)])}async function At(e,t,n=[]){return jt([...n,...t,Tt(e)])}async function jt(e){let t=new Map;for(let n of e){let e;try{e=await G.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let r=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of r.sort()){let r=K.join(n,e,`SKILL.md`),i;try{i=await G.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a;try{a=Ot(i)}catch(t){Dt(e,r,t);continue}t.set(e,{name:e,description:a,location:r})}}return Array.from(t.values()).slice(0,50)}async function Mt(e,t){let n=t.trim();if(!n)return;let r=(await jt(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:K.dirname(r.location)}}async function Nt(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=K.resolve(r),a=K.basename(i)===`SKILL.md`?i:K.join(i,`SKILL.md`);if(K.basename(a)!==`SKILL.md`)return;let o;try{o=await G.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s;try{s=Ot(o)}catch(e){Dt(n,a,e);return}return{skill:{name:n,description:s,location:a},rootDir:K.dirname(a)}}async function Pt(e,t,n){let r=n?.trim()?await Nt(t,n):await Mt(e,t);if(!r)return;let i=await G.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function Ft(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
|
|
@@ -6,8 +6,8 @@ import{A as e,C as t,D as n,E as r,F as i,I as a,M as o,N as s,O as c,P as l,S a
|
|
|
6
6
|
`)}\n</available_skills>`}var It=class{turn=null;wallClock={activeGoalId:null,lastAccountedAt:Date.now()};resetWallClock(){this.wallClock.lastAccountedAt=Date.now()}markActiveGoal(e,t,n){e&&(this.turn&&this.turn.turnId===e?(this.turn.activeGoalId=t,this.turn.lastTokenUsage=n):this.turn={turnId:e,activeGoalId:t,lastTokenUsage:n}),this.wallClock.activeGoalId!==t&&this.resetWallClock(),this.wallClock.activeGoalId=t}clearActiveGoal(){this.turn&&(this.turn.activeGoalId=null),this.wallClock.activeGoalId=null,this.resetWallClock()}tokenDeltaSinceLastAccounting(e){if(!this.turn||!this.turn.activeGoalId)return 0;let t=this.turn.lastTokenUsage;return Math.max(0,e.input-t.input)+Math.max(0,e.output-t.output)}timeDeltaSecondsSinceLastAccounting(){if(!this.wallClock.activeGoalId)return 0;let e=Date.now()-this.wallClock.lastAccountedAt;return Math.floor(e/1e3)}markAccounted(e,t){this.turn&&(this.turn.lastTokenUsage=e),t>0&&(this.wallClock.lastAccountedAt+=t*1e3),this.wallClock.lastAccountedAt>Date.now()&&(this.wallClock.lastAccountedAt=Date.now())}};async function Lt(e,t,n,r,i){let a=await B(e,t,{storeName:i?.storeName});if(!a)return{goal:null,budgetLimited:!1};let o=n.turn?.activeGoalId??n.wallClock.activeGoalId;if(o&&o!==a.goalId)return{goal:a,budgetLimited:!1};let s=n.tokenDeltaSinceLastAccounting(r),c=n.timeDeltaSecondsSinceLastAccounting();if(s<=0&&c<=0)return{goal:a,budgetLimited:!1};let l=a.tokensUsed+s,u=a.timeUsedSeconds+c,d=a.status,f=!1;a.tokenBudget!==null&&l>=a.tokenBudget&&a.status===`active`&&(d=`budget_limited`,f=!0);let p=await L(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}function Rt(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function zt(e,t){let n=Rt(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=String(e.tokensUsed),a=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed));return[`<goal_context>`,``,`The user's thread goal is still active. Continue working toward the objective below.`,``,`<objective>`,n,`</objective>`,``,`Token budget: ${r}`,`Tokens used: ${i}`,`Tokens remaining: ${a}`,`Time used: ${e.timeUsedSeconds}s`,``,`Rules:`,`- Keep the full objective intact; do not redefine it as a smaller task.`,`- Use the current worktree, files, command output, and test results as authoritative evidence of progress.`,`- Do not rely solely on conversation memory to assess completion.`,`- Perform a completion audit: check each requirement in the objective against actual state.`,`- Only call update_goal with status "complete" when the objective is fully achieved and verified.`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress and the goal remains active.`,`- Do not inform the user about this continuation context; treat it as internal steering.`,``,`</goal_context>`].join(`
|
|
7
7
|
`)}function Bt(e,t){let n=Rt(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=String(e.tokensUsed);return[`<goal_context>`,``,`The token budget for the current thread goal has been exhausted.`,`The goal status has been set to "budget_limited" automatically.`,``,`<objective>`,n,`</objective>`,``,`Token budget: ${r}`,`Tokens used: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Instructions:`,`- Wrap up the current turn soon. Do not start new substantive work.`,`- Summarize progress made, any blockers, and what would be needed next.`,`- Do NOT call update_goal(complete) unless the objective is truly achieved.`,`- The user can increase the budget or resume the goal later via the CLI.`,``,`</goal_context>`].join(`
|
|
8
8
|
`)}function Vt(e,t){let n=Rt(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed));return[`<goal_context>`,``,`The thread goal objective has been edited by the user.`,`The following objective supersedes any previous thread goal objective.`,`Adjust your work direction accordingly.`,``,`<untrusted_objective>`,n,`</untrusted_objective>`,``,`Token budget: ${r}`,`Tokens remaining: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Do not call update_goal unless the updated goal is actually complete.`,``,`</goal_context>`].join(`
|
|
9
|
-
`)}function Ht(e){return{role:`user`,content:e}}function Ut(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const Wt=`AIMAX_GOAL_CONTINUATION`;var Gt=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};function Kt(){let e=process.env[Wt];return e===void 0||e===``||e!==`0`}async function qt(e,t,n,r){if(!Kt()||n.continuationCount>=Fe)return!1;let i=await B(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-CClsJSJO.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Jt(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Yt(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await qt(n,r,a,{storeName:i}))return!1;let u=await B(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await H(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=Ht(p?Bt(u,f):zt(u,f));a.continuationCount++;let h=await c(m.content);if(a.lastTurnHadOutput=Jt(h),p&&(a.budgetWrapUpDone=!0),l&&await l({input:h.inputTokens,output:h.outputTokens,total:h.inputTokens+h.outputTokens}),a.continuationCount>=Fe){let e=await B(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-B36KsoVO.js`).then(e=>e.i),{appendGoalEvent:o}=await import(`./goal-events-PYGTADzY.js`).then(e=>e.r),s={storeName:i,eventSource:`runner`};await t(n,r,{status:`paused`},s),await o(n,r,{goalId:e?.goalId??null,action:`continuation_paused`,status:`paused`,source:`runner`,detail:{continuationCount:a.continuationCount}},s),console.error(`goal continuation limit reached (${Fe}), goal paused`)}}return!0}async function Xt(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function Zt(e,t,n,r){let i=await B(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=Ht(Vt(i,await H(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function Qt(e,t,n){(await B(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await L(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}async function $t(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function en(e,t,n){let r=n.before?.status??null,i=n.after?.status??null,a=n.before?.goalId,o=n.after?.goalId;r===i&&a===o||await $t(e,t,{action:n.action,goal:n.after??null})}function tn(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e)o.role===`user`?t+=1:o.role===`assistant`?n+=1:o.role===`tool_result`?r+=1:o.role===`compaction`?i+=1:a+=1;return{userTurnCount:t,assistantTurnCount:n,toolResultCount:r,compactionCount:i,otherEntryCount:a,totalEntryCount:e.length}}function nn(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(dn(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}fn(a)&&(r+=1,a.isError&&(i+=1))}let a=Array.from(t).sort();return{toolCallCount:n,distinctToolCount:a.length,toolNames:a,toolResultCount:r,failedToolResultCount:i}}function rn(e,t={}){let n=ln(t.limit,`limit`),r=un(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!fn(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:cn(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function an(e,t){let n=un(e,`totalEntryCount`);return typeof t!=`number`||!Number.isFinite(t)?{startIndex:0,endIndex:n}:{startIndex:Math.min(n,Math.max(0,Math.floor(t))),endIndex:n}}function on(e,t=80){let n=un(e,`totalEntryCount`),r=un(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function sn(e,t){return e.slice(t.startIndex,t.endIndex)}function cn(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function ln(e,t){return e===void 0?1/0:un(e,t)}function un(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function dn(e){return e.role===`assistant`}function fn(e){return e.role===`tool_result`}const pn=24e3;async function mn(e){return Sn({params:e,kind:`current_run`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function hn(e){return Sn({params:e,kind:`recent_conversation`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function gn(e){return Sn({params:e,kind:`transcript_range`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function _n(e){let t=An(e),n=await yn(e),r=await En(n.filePath,t.maxBytes);return{kind:`tool_result`,toolCallId:n.reference.toolCallId,toolName:n.reference.toolName,storagePath:n.reference.storagePath,content:r.content,originalBytes:r.originalBytes,returnedBytes:Buffer.byteLength(r.content,`utf-8`),truncated:r.truncated,limits:t,contextFiles:bn(e.dataDir,e.sessionId,e.sessionOptions)}}function vn(e){return{maxEntries:jn(e?.maxEntries??80,`limits.maxEntries`),maxBytes:jn(e?.maxBytes??pn,`limits.maxBytes`)}}async function yn(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=Cn(await wn(e.dataDir,e.sessionId,e.sessionOptions),{toolCallId:e.toolCallId,storagePath:e.storagePath});if(!t)throw Error(`Requested tool result is not referenced by this session transcript or context.`);return{reference:t,filePath:await Tn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function bn(t,n,r){return{transcriptPath:e(t,n,r),contextSnapshotPath:h(t,n,r),toolResultsDir:S(t,n,r)}}function xn(e,t,n){let r=Mn(e.startIndex,`startIndex`),i=Mn(e.endIndex,`endIndex`);if(r<0||i<r||i>t)throw Error(`Requested transcript range is outside transcript bounds 0..${t}.`);if(i-r>n)throw Error(`Requested transcript range exceeds maximum of ${n} entries.`);return{startIndex:r,endIndex:i}}function Sn(e){let t=An(e.params),n=xn(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=Dn(r,t.maxBytes);return{kind:e.kind,range:n,entries:i.entries,entryCount:i.entries.length,rangeEntryCount:r.length,totalEntryCount:e.transcript.length,returnedBytes:i.returnedBytes,truncated:i.truncated,limits:t,contextFiles:bn(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function Cn(e,t){if(t.toolCallId&&t.storagePath){let n=e.find(e=>e.toolCallId===t.toolCallId&&e.storagePath===t.storagePath);if(n)return n;let r=e.some(e=>e.toolCallId===t.toolCallId),i=e.some(e=>e.storagePath===t.storagePath);if(r&&i)throw Error(`Requested toolCallId and storagePath do not reference the same tool result.`);return}return e.find(e=>t.toolCallId?e.toolCallId===t.toolCallId:e.storagePath===t.storagePath)}async function wn(e,t,n){let[r,i]=await Promise.all([m(e,t,n),j(e,t,n)]),a=new Map;for(let e of r)Fn(e)&&e.toolResultRef?.sessionId===t&&a.set(In(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(In(e),e);return Array.from(a.values())}async function Tn(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(K.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=S(e.dataDir,e.sessionId,e.sessionOptions),n=d(e.dataDir,e.sessionId,e.sessionOptions),r=K.resolve(e.dataDir,e.reference.storagePath);if(!Pn(K.resolve(t),r))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Pn(K.resolve(n),r))throw Error(`Referenced tool result is outside the session directory.`);let[i,a,o]=await Promise.all([Nn(t),Nn(n),Nn(r)]);if(!Pn(i,o))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Pn(a,o))throw Error(`Referenced tool result resolves outside the session directory.`);return o}async function En(e,t){let n=await G.stat(e),r=await G.open(e,`r`);try{let e=Buffer.alloc(t+1),{bytesRead:i}=await r.read(e,0,t+1,0),a=Math.min(i,t);return{content:kn(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function Dn(e,t){let n=[],r=0,i=!1;for(let a of e){let e={...a,content:``},o=Buffer.byteLength(JSON.stringify(e),`utf-8`);if(r+o>=t){i=!0;break}let s=t-r-o,c=On(a.content,s);c.truncated&&(i=!0);let l={...a,content:c.value},u=Buffer.byteLength(JSON.stringify(l),`utf-8`);if(n.push(l),r+=u,c.truncated)break}return n.length<e.length&&(i=!0),{entries:n,returnedBytes:r,truncated:i}}function On(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:kn(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function kn(e){let t=new Ge(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function An(e){return vn(e.limits)}function jn(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function Mn(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function Nn(e){try{return await G.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${Ln(e)}`)}}function Pn(e,t){let n=K.relative(e,t);return n===``||!n.startsWith(`..`)&&!K.isAbsolute(n)}function Fn(e){return e.role===`tool_result`}function In(e){return`${e.toolCallId}\n${e.storagePath}`}function Ln(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Rn(e){return K.join(e,`.aimax`,`auto-skills`)}function zn(e){return K.join(e,`categories.json`)}function Bn(e){return K.join(e,`.auto_skills_prompt_snapshot.json`)}const Vn=/^[a-z0-9][a-z0-9-]*$/,Hn=/^[a-z0-9][a-z0-9-]*$/;function Y(e){let t=e.trim();if(!t)throw Error(`Auto-skill category path cannot be empty.`);if(t.length>180)throw Error(`Auto-skill category path is too long.`);if(t.includes(`\\`)||K.win32.isAbsolute(t)||K.posix.isAbsolute(t))throw Error(`Invalid auto-skill category path: ${e}`);let n=t.split(`/`);if(n.length!==1)throw Error(`Auto-skill category path must be a single slug.`);for(let t of n){if(!t||t===`.`||t===`..`||t.startsWith(`.`))throw Error(`Invalid auto-skill category path: ${e}`);if(!Vn.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function Un(e){let t=e.trim();if(!t)throw Error(`Auto-skill name cannot be empty.`);if(t.length>80)throw Error(`Auto-skill name is too long.`);if(t.includes(`/`)||t.includes(`\\`)||t===`.`||t===`..`||t.startsWith(`.`)||!Hn.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Wn(e,t){return`auto:${Y(e)}/${Un(t)}`}function Gn(e){let t=e.trim();if(!t.startsWith(`auto:`))throw Error(`Invalid auto-skill id: ${e}`);let n=t.slice(5),r=n.indexOf(`/`);if(r<=0||r===n.length-1)throw Error(`Invalid auto-skill id: ${e}`);if(n.indexOf(`/`,r+1)!==-1)throw Error(`Auto-skill id category path must be a single slug.`);let i=Y(n.slice(0,r)),a=Un(n.slice(r+1));return{skillId:Wn(i,a),categoryPath:i,skillName:a}}function Kn(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function qn(e,t,n){let r=K.resolve(e),i=K.resolve(r,...Y(t).split(`/`),Un(n));return Yn(r,i),i}function Jn(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||K.win32.isAbsolute(n)||K.posix.isAbsolute(n))throw Error(`Invalid auto-skill resource path: ${t}`);let r=n.split(`/`);for(let e of r)if(!e||e===`.`||e===`..`||e.startsWith(`.`))throw Error(`Invalid auto-skill resource path: ${t}`);let i=K.resolve(e),a=K.resolve(i,...r);return Yn(i,a),a}function Yn(e,t){let n=K.resolve(e),r=K.resolve(t),i=K.relative(n,r);if(i.startsWith(`..`)||K.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Xn(e){let t=zn(e),n;try{n=await G.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let r=JSON.parse(n);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Auto-skill categories.json must be a JSON object.`);return Object.entries(r).map(([e,t])=>{let n=Y(e),r=Qn(t);return{path:n,name:n.split(`/`).at(-1)??n,description:r.description,createdBy:r.createdBy}}).sort((e,t)=>e.path.localeCompare(t.path))}function Zn(e){return new Map(e.map(e=>[e.path,e]))}function Qn(e){return typeof e==`string`?{description:e.trim()}:!e||typeof e!=`object`||Array.isArray(e)?{description:``}:{description:typeof e.description==`string`?e.description.trim():``,createdBy:typeof e.createdBy==`string`?e.createdBy.trim():void 0}}const $n=32*1024,er=new Map;function tr(e){return new rr(e)}async function nr(e){let t=K.resolve(e);for(let e of Array.from(er.keys()))e.startsWith(`${t}|`)&&er.delete(e);await G.rm(Bn(t),{force:!0}).catch(()=>{})}var rr=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=K.resolve(e.rootDir??Rn(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return ar(Zn((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?Y(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>or(e.categoryPath,t)).map(ir)}async autoSkillSearch(e){let t=e.query.trim().toLowerCase();if(!t)return[];let n=Math.max(1,e.limit??5);return(await this.visibleEntries()).map(e=>({entry:e,score:sr(e,t)})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score||e.entry.skillId.localeCompare(t.entry.skillId)).slice(0,n).map(({entry:e,score:t})=>({...ir(e),score:t}))}async autoSkillView(e){let t=Gn(e.skillId),n=(await this.visibleEntries()).find(e=>e.skillId===t.skillId);if(!n)throw Error(`Unknown auto-skill: ${e.skillId}`);if(e.filePath?.trim()){let t=Jn(n.skillDir,e.filePath),r=await gr(t,this.maxResourceBytes);return{...ir(n),status:n.status,content:r,path:yr(K.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:yr(K.relative(n.skillDir,t))}}let r=await gr(n.skillFile,this.maxSkillBytes);return{...ir(n),status:n.status,content:r,path:yr(K.relative(this.rootDir,n.skillFile)),skillDir:n.skillDir,tags:n.tags,relatedSkills:n.relatedSkills}}async loadIndex(){let e=await this.loadIndexState();return this.visibleEntriesFrom(e.entries)}async loadIndexState(e=!1){let t=this.optionsHash(),n=`${this.rootDir}|${t}`,r=await cr(this.rootDir),i=er.get(n);if(!e&&i&&pr(i.manifest,r))return i;let a=e?void 0:await dr(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return er.set(n,e),e}let o=await Xn(this.rootDir),s=Zn(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return er.set(n,c),await fr(this.rootDir,c).catch(()=>{}),c}async parseEntriesFromManifest(e){let t=e.filter(e=>e.kind===`skill`).map(e=>e.filePath),n=[];for(let e of t){let t=await this.loadEntry(e);t&&n.push(t)}return n.sort((e,t)=>e.skillId.localeCompare(t.skillId))}async visibleEntries(){let e=await this.loadIndex();return this.visibleEntriesFrom(e)}visibleEntriesFrom(e){return this.includeArchived?e:e.filter(e=>e.status===`active`)}optionsHash(){return Sr({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:$n})}async loadEntry(e){try{let t=K.dirname(e),n=Un(K.basename(t)),r=yr(K.relative(this.rootDir,t)),i=Y(K.posix.dirname(r)),a=Wn(i,n),o=K.join(t,`metadata.json`),s=await mr(o);if(s?.skillId&&Gn(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&Y(s.categoryPath)!==i)throw Error(`metadata categoryPath does not match path for ${a}`);if(s?.source&&s.source!==`auto`)throw Error(`metadata source must be auto for ${a}`);let c=Kn(s?.status);return{skillId:a,name:n,description:_r(await hr(e,$n)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:vr(s?.tags),relatedSkills:vr(s?.relatedSkills),confidence:typeof s?.confidence==`number`?s.confidence:void 0,createdAt:typeof s?.createdAt==`string`?s.createdAt:void 0,updatedAt:typeof s?.updatedAt==`string`?s.updatedAt:void 0}}catch(t){process.stderr.write(`[auto-skills] skipped ${e}: ${br(t)}\n`);return}}};function ir(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function ar(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function or(e,t){return t?e===t:!0}function sr(e,t){let n=t.split(/\s+/).filter(Boolean),r=e.name.toLowerCase(),i=e.description.toLowerCase(),a=e.categoryPath.toLowerCase(),o=e.tags.join(` `).toLowerCase(),s=0;r===t&&(s+=80),r.includes(t)&&(s+=30),i.includes(t)&&(s+=20),a.includes(t)&&(s+=10),o.includes(t)&&(s+=10);for(let e of n)r.includes(e)&&(s+=8),i.includes(e)&&(s+=5),a.includes(e)&&(s+=3),o.includes(e)&&(s+=3);return s}async function cr(e){let t;try{t=await G.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await ur(K.join(e,`categories.json`),`categories`,n),await lr(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function lr(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=K.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await ur(t,`skill`,n),await ur(K.join(e,`metadata.json`),`metadata`,n),await ur(K.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await G.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await lr(t,i,n)}}async function ur(e,t,n){try{let r=await G.stat(e);if(!r.isFile())return;n.push({filePath:e,kind:t,size:r.size,mtimeMs:r.mtimeMs})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}}async function dr(e,t,n){let r;try{r=await G.readFile(Bn(e),`utf-8`)}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=JSON.parse(r);return e.version!==1||e.optionsHash!==t||!Array.isArray(e.entries)||!Array.isArray(e.categories)||!Array.isArray(e.manifest)||!pr(e.manifest,n)?void 0:e}catch{return}}async function fr(e,t){if(!await xr(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await G.writeFile(Bn(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function pr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r.filePath!==i.filePath||r.kind!==i.kind||r.size!==i.size||r.mtimeMs!==i.mtimeMs)return!1}return!0}async function mr(e){try{let t=await G.readFile(e,`utf-8`),n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}async function hr(e,t){let n=await G.open(e,`r`);try{let e=await n.stat(),r=Math.min(e.size,t),i=Buffer.alloc(r);return await n.read(i,0,r,0),i.toString(`utf-8`)}finally{await n.close()}}async function gr(e,t){if((await G.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return G.readFile(e,`utf-8`)}function _r(e){let t=He(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
|
|
10
|
-
`)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function vr(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function yr(e){return e.split(K.sep).join(`/`)}function br(e){return e instanceof Error?e.message:String(e)}async function xr(e){try{return await G.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function Sr(e){return Ue(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function Cr(e,t,n,r){let i={"Client-Code":`AIMax`,"X-Session-Id":t};return n&&(i[`X-Message-Id`]=n),r&&(i[`X-Channel`]=r),{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:32768,headers:i,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}const wr=`/aimax/agents`,Tr=/^[a-z]+(?:-[a-z]+)*$/;function Er(e){let t=[{dir:e.systemAgentsDir??wr,source:`system`},{dir:K.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:K.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function Dr(e){let t=new Map;for(let n of Er(e)){let e=await jr(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function Or(e={}){let t=e.allAgents??e.availableAgents??[],n=Fr(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>Nr(n,e),findAny:e=>Nr(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function kr(e){return!!(e&&typeof e==`object`&&Array.isArray(e.allAgents)&&Array.isArray(e.availableAgents)&&typeof e.findPublic==`function`&&typeof e.findAny==`function`&&typeof e.stats==`function`)}async function Ar(e){return kr(e.agentPolicy)?e.agentPolicy:Or({allAgents:await Dr(e)})}async function jr(e,t){let n;try{n=await G.readdir(e,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}let r=[];for(let i of n){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let n=K.join(e,i.name),a=Mr(await G.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function Mr(e,t){let n=He(e),r=Br(n.data.name)?.trim(),i=Br(n.data.description)?.trim();if(!r||!Tr.test(r)||!i)return;let a=Br(n.data.model)?.trim(),o=Br(n.data.initPrompt)?.trim()??Br(n.data.initialPrompt)?.trim(),s=Vr(n.data.maxTurns),c=Hr(n.data.tools),l=Hr(n.data.disallowedTools),u=Hr(n.data.skills),d=Ur(n.data.visibility);if(!(n.data.visibility!==void 0&&!d))return{name:r,description:i,visibility:d??`public`,...c?{tools:c}:{},...l?{disallowedTools:l}:{},...a&&a!==`inherit`?{model:a}:{},...s?{maxTurns:s}:{},...o?{initPrompt:o}:{},...u?{skills:u}:{},systemPrompt:n.content.trim(),sourcePath:t.sourcePath,source:t.source}}function Nr(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Pr(e)===`public`))}function Pr(e){return e.visibility??`public`}function Fr(e){return e.filter(e=>Pr(e)===`public`)}function Ir(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Lr(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Wr)):void 0,r=new Set((t.disallowedTools??[]).map(Wr));return e.filter(e=>{let t=typeof e.name==`string`?Wr(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Rr(e){let t=Fr(e).filter(e=>e.source!==`system`);return t.length===0?``:[`## Custom Agents`,`The following custom agents are currently effective.`,"When delegating with `subagent_spawn`, you may set the optional `agent` field only to one of the exact names listed below.","Do not guess, invent, paraphrase, translate, or synthesize agent names. If no listed custom agent clearly matches, leave `agent` unset and delegate normally.","When the user's message contains `@<agent-name>` (e.g. `@secure-code-reviewer`) and the name matches one of the listed custom agents, you MUST
|
|
9
|
+
`)}function Ht(e){return{role:`user`,content:e}}function Ut(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const Wt=`AIMAX_GOAL_CONTINUATION`;var Gt=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};function Kt(){let e=process.env[Wt];return e===void 0||e===``||e!==`0`}async function qt(e,t,n,r){if(!Kt()||n.continuationCount>=Fe)return!1;let i=await B(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-DjXWnxJY.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Jt(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Yt(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await qt(n,r,a,{storeName:i}))return!1;let u=await B(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await H(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=Ht(p?Bt(u,f):zt(u,f));a.continuationCount++;let h=await c(m.content);if(a.lastTurnHadOutput=Jt(h),p&&(a.budgetWrapUpDone=!0),l&&await l({input:h.inputTokens,output:h.outputTokens,total:h.inputTokens+h.outputTokens}),a.continuationCount>=Fe){let e=await B(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-DxaeZmiE.js`).then(e=>e.i),{appendGoalEvent:o}=await import(`./goal-events-Bdf1BDep.js`).then(e=>e.r),s={storeName:i,eventSource:`runner`};await t(n,r,{status:`paused`},s),await o(n,r,{goalId:e?.goalId??null,action:`continuation_paused`,status:`paused`,source:`runner`,detail:{continuationCount:a.continuationCount}},s),console.error(`goal continuation limit reached (${Fe}), goal paused`)}}return!0}async function Xt(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function Zt(e,t,n,r){let i=await B(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=Ht(Vt(i,await H(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function Qt(e,t,n){(await B(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await L(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}async function $t(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function en(e,t,n){let r=n.before?.status??null,i=n.after?.status??null,a=n.before?.goalId,o=n.after?.goalId;r===i&&a===o||await $t(e,t,{action:n.action,goal:n.after??null})}function tn(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e)o.role===`user`?t+=1:o.role===`assistant`?n+=1:o.role===`tool_result`?r+=1:o.role===`compaction`?i+=1:a+=1;return{userTurnCount:t,assistantTurnCount:n,toolResultCount:r,compactionCount:i,otherEntryCount:a,totalEntryCount:e.length}}function nn(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(dn(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}fn(a)&&(r+=1,a.isError&&(i+=1))}let a=Array.from(t).sort();return{toolCallCount:n,distinctToolCount:a.length,toolNames:a,toolResultCount:r,failedToolResultCount:i}}function rn(e,t={}){let n=ln(t.limit,`limit`),r=un(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!fn(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:cn(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function an(e,t){let n=un(e,`totalEntryCount`);return typeof t!=`number`||!Number.isFinite(t)?{startIndex:0,endIndex:n}:{startIndex:Math.min(n,Math.max(0,Math.floor(t))),endIndex:n}}function on(e,t=80){let n=un(e,`totalEntryCount`),r=un(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function sn(e,t){return e.slice(t.startIndex,t.endIndex)}function cn(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function ln(e,t){return e===void 0?1/0:un(e,t)}function un(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function dn(e){return e.role===`assistant`}function fn(e){return e.role===`tool_result`}const pn=24e3;async function mn(e){return Sn({params:e,kind:`current_run`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function hn(e){return Sn({params:e,kind:`recent_conversation`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function gn(e){return Sn({params:e,kind:`transcript_range`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function _n(e){let t=An(e),n=await yn(e),r=await En(n.filePath,t.maxBytes);return{kind:`tool_result`,toolCallId:n.reference.toolCallId,toolName:n.reference.toolName,storagePath:n.reference.storagePath,content:r.content,originalBytes:r.originalBytes,returnedBytes:Buffer.byteLength(r.content,`utf-8`),truncated:r.truncated,limits:t,contextFiles:bn(e.dataDir,e.sessionId,e.sessionOptions)}}function vn(e){return{maxEntries:jn(e?.maxEntries??80,`limits.maxEntries`),maxBytes:jn(e?.maxBytes??pn,`limits.maxBytes`)}}async function yn(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=Cn(await wn(e.dataDir,e.sessionId,e.sessionOptions),{toolCallId:e.toolCallId,storagePath:e.storagePath});if(!t)throw Error(`Requested tool result is not referenced by this session transcript or context.`);return{reference:t,filePath:await Tn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function bn(t,n,r){return{transcriptPath:e(t,n,r),contextSnapshotPath:h(t,n,r),toolResultsDir:S(t,n,r)}}function xn(e,t,n){let r=Mn(e.startIndex,`startIndex`),i=Mn(e.endIndex,`endIndex`);if(r<0||i<r||i>t)throw Error(`Requested transcript range is outside transcript bounds 0..${t}.`);if(i-r>n)throw Error(`Requested transcript range exceeds maximum of ${n} entries.`);return{startIndex:r,endIndex:i}}function Sn(e){let t=An(e.params),n=xn(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=Dn(r,t.maxBytes);return{kind:e.kind,range:n,entries:i.entries,entryCount:i.entries.length,rangeEntryCount:r.length,totalEntryCount:e.transcript.length,returnedBytes:i.returnedBytes,truncated:i.truncated,limits:t,contextFiles:bn(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function Cn(e,t){if(t.toolCallId&&t.storagePath){let n=e.find(e=>e.toolCallId===t.toolCallId&&e.storagePath===t.storagePath);if(n)return n;let r=e.some(e=>e.toolCallId===t.toolCallId),i=e.some(e=>e.storagePath===t.storagePath);if(r&&i)throw Error(`Requested toolCallId and storagePath do not reference the same tool result.`);return}return e.find(e=>t.toolCallId?e.toolCallId===t.toolCallId:e.storagePath===t.storagePath)}async function wn(e,t,n){let[r,i]=await Promise.all([m(e,t,n),j(e,t,n)]),a=new Map;for(let e of r)Fn(e)&&e.toolResultRef?.sessionId===t&&a.set(In(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(In(e),e);return Array.from(a.values())}async function Tn(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(K.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=S(e.dataDir,e.sessionId,e.sessionOptions),n=d(e.dataDir,e.sessionId,e.sessionOptions),r=K.resolve(e.dataDir,e.reference.storagePath);if(!Pn(K.resolve(t),r))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Pn(K.resolve(n),r))throw Error(`Referenced tool result is outside the session directory.`);let[i,a,o]=await Promise.all([Nn(t),Nn(n),Nn(r)]);if(!Pn(i,o))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Pn(a,o))throw Error(`Referenced tool result resolves outside the session directory.`);return o}async function En(e,t){let n=await G.stat(e),r=await G.open(e,`r`);try{let e=Buffer.alloc(t+1),{bytesRead:i}=await r.read(e,0,t+1,0),a=Math.min(i,t);return{content:kn(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function Dn(e,t){let n=[],r=0,i=!1;for(let a of e){let e={...a,content:``},o=Buffer.byteLength(JSON.stringify(e),`utf-8`);if(r+o>=t){i=!0;break}let s=t-r-o,c=On(a.content,s);c.truncated&&(i=!0);let l={...a,content:c.value},u=Buffer.byteLength(JSON.stringify(l),`utf-8`);if(n.push(l),r+=u,c.truncated)break}return n.length<e.length&&(i=!0),{entries:n,returnedBytes:r,truncated:i}}function On(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:kn(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function kn(e){let t=new Ge(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function An(e){return vn(e.limits)}function jn(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function Mn(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function Nn(e){try{return await G.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${Ln(e)}`)}}function Pn(e,t){let n=K.relative(e,t);return n===``||!n.startsWith(`..`)&&!K.isAbsolute(n)}function Fn(e){return e.role===`tool_result`}function In(e){return`${e.toolCallId}\n${e.storagePath}`}function Ln(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Rn(e){return K.join(e,`.aimax`,`auto-skills`)}function zn(e){return K.join(e,`categories.json`)}function Bn(e){return K.join(e,`.auto_skills_prompt_snapshot.json`)}const Vn=/^[a-z0-9][a-z0-9-]*$/,Hn=/^[a-z0-9][a-z0-9-]*$/;function Y(e){let t=e.trim();if(!t)throw Error(`Auto-skill category path cannot be empty.`);if(t.length>180)throw Error(`Auto-skill category path is too long.`);if(t.includes(`\\`)||K.win32.isAbsolute(t)||K.posix.isAbsolute(t))throw Error(`Invalid auto-skill category path: ${e}`);let n=t.split(`/`);if(n.length!==1)throw Error(`Auto-skill category path must be a single slug.`);for(let t of n){if(!t||t===`.`||t===`..`||t.startsWith(`.`))throw Error(`Invalid auto-skill category path: ${e}`);if(!Vn.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function Un(e){let t=e.trim();if(!t)throw Error(`Auto-skill name cannot be empty.`);if(t.length>80)throw Error(`Auto-skill name is too long.`);if(t.includes(`/`)||t.includes(`\\`)||t===`.`||t===`..`||t.startsWith(`.`)||!Hn.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Wn(e,t){return`auto:${Y(e)}/${Un(t)}`}function Gn(e){let t=e.trim();if(!t.startsWith(`auto:`))throw Error(`Invalid auto-skill id: ${e}`);let n=t.slice(5),r=n.indexOf(`/`);if(r<=0||r===n.length-1)throw Error(`Invalid auto-skill id: ${e}`);if(n.indexOf(`/`,r+1)!==-1)throw Error(`Auto-skill id category path must be a single slug.`);let i=Y(n.slice(0,r)),a=Un(n.slice(r+1));return{skillId:Wn(i,a),categoryPath:i,skillName:a}}function Kn(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function qn(e,t,n){let r=K.resolve(e),i=K.resolve(r,...Y(t).split(`/`),Un(n));return Yn(r,i),i}function Jn(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||K.win32.isAbsolute(n)||K.posix.isAbsolute(n))throw Error(`Invalid auto-skill resource path: ${t}`);let r=n.split(`/`);for(let e of r)if(!e||e===`.`||e===`..`||e.startsWith(`.`))throw Error(`Invalid auto-skill resource path: ${t}`);let i=K.resolve(e),a=K.resolve(i,...r);return Yn(i,a),a}function Yn(e,t){let n=K.resolve(e),r=K.resolve(t),i=K.relative(n,r);if(i.startsWith(`..`)||K.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Xn(e){let t=zn(e),n;try{n=await G.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let r=JSON.parse(n);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Auto-skill categories.json must be a JSON object.`);return Object.entries(r).map(([e,t])=>{let n=Y(e),r=Qn(t);return{path:n,name:n.split(`/`).at(-1)??n,description:r.description,createdBy:r.createdBy}}).sort((e,t)=>e.path.localeCompare(t.path))}function Zn(e){return new Map(e.map(e=>[e.path,e]))}function Qn(e){return typeof e==`string`?{description:e.trim()}:!e||typeof e!=`object`||Array.isArray(e)?{description:``}:{description:typeof e.description==`string`?e.description.trim():``,createdBy:typeof e.createdBy==`string`?e.createdBy.trim():void 0}}const $n=32*1024,er=new Map;function tr(e){return new rr(e)}async function nr(e){let t=K.resolve(e);for(let e of Array.from(er.keys()))e.startsWith(`${t}|`)&&er.delete(e);await G.rm(Bn(t),{force:!0}).catch(()=>{})}var rr=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=K.resolve(e.rootDir??Rn(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return ar(Zn((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?Y(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>or(e.categoryPath,t)).map(ir)}async autoSkillSearch(e){let t=e.query.trim().toLowerCase();if(!t)return[];let n=Math.max(1,e.limit??5);return(await this.visibleEntries()).map(e=>({entry:e,score:sr(e,t)})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score||e.entry.skillId.localeCompare(t.entry.skillId)).slice(0,n).map(({entry:e,score:t})=>({...ir(e),score:t}))}async autoSkillView(e){let t=Gn(e.skillId),n=(await this.visibleEntries()).find(e=>e.skillId===t.skillId);if(!n)throw Error(`Unknown auto-skill: ${e.skillId}`);if(e.filePath?.trim()){let t=Jn(n.skillDir,e.filePath),r=await gr(t,this.maxResourceBytes);return{...ir(n),status:n.status,content:r,path:yr(K.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:yr(K.relative(n.skillDir,t))}}let r=await gr(n.skillFile,this.maxSkillBytes);return{...ir(n),status:n.status,content:r,path:yr(K.relative(this.rootDir,n.skillFile)),skillDir:n.skillDir,tags:n.tags,relatedSkills:n.relatedSkills}}async loadIndex(){let e=await this.loadIndexState();return this.visibleEntriesFrom(e.entries)}async loadIndexState(e=!1){let t=this.optionsHash(),n=`${this.rootDir}|${t}`,r=await cr(this.rootDir),i=er.get(n);if(!e&&i&&pr(i.manifest,r))return i;let a=e?void 0:await dr(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return er.set(n,e),e}let o=await Xn(this.rootDir),s=Zn(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return er.set(n,c),await fr(this.rootDir,c).catch(()=>{}),c}async parseEntriesFromManifest(e){let t=e.filter(e=>e.kind===`skill`).map(e=>e.filePath),n=[];for(let e of t){let t=await this.loadEntry(e);t&&n.push(t)}return n.sort((e,t)=>e.skillId.localeCompare(t.skillId))}async visibleEntries(){let e=await this.loadIndex();return this.visibleEntriesFrom(e)}visibleEntriesFrom(e){return this.includeArchived?e:e.filter(e=>e.status===`active`)}optionsHash(){return Sr({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:$n})}async loadEntry(e){try{let t=K.dirname(e),n=Un(K.basename(t)),r=yr(K.relative(this.rootDir,t)),i=Y(K.posix.dirname(r)),a=Wn(i,n),o=K.join(t,`metadata.json`),s=await mr(o);if(s?.skillId&&Gn(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&Y(s.categoryPath)!==i)throw Error(`metadata categoryPath does not match path for ${a}`);if(s?.source&&s.source!==`auto`)throw Error(`metadata source must be auto for ${a}`);let c=Kn(s?.status);return{skillId:a,name:n,description:_r(await hr(e,$n)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:vr(s?.tags),relatedSkills:vr(s?.relatedSkills),confidence:typeof s?.confidence==`number`?s.confidence:void 0,createdAt:typeof s?.createdAt==`string`?s.createdAt:void 0,updatedAt:typeof s?.updatedAt==`string`?s.updatedAt:void 0}}catch(t){process.stderr.write(`[auto-skills] skipped ${e}: ${br(t)}\n`);return}}};function ir(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function ar(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function or(e,t){return t?e===t:!0}function sr(e,t){let n=t.split(/\s+/).filter(Boolean),r=e.name.toLowerCase(),i=e.description.toLowerCase(),a=e.categoryPath.toLowerCase(),o=e.tags.join(` `).toLowerCase(),s=0;r===t&&(s+=80),r.includes(t)&&(s+=30),i.includes(t)&&(s+=20),a.includes(t)&&(s+=10),o.includes(t)&&(s+=10);for(let e of n)r.includes(e)&&(s+=8),i.includes(e)&&(s+=5),a.includes(e)&&(s+=3),o.includes(e)&&(s+=3);return s}async function cr(e){let t;try{t=await G.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await ur(K.join(e,`categories.json`),`categories`,n),await lr(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function lr(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=K.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await ur(t,`skill`,n),await ur(K.join(e,`metadata.json`),`metadata`,n),await ur(K.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await G.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await lr(t,i,n)}}async function ur(e,t,n){try{let r=await G.stat(e);if(!r.isFile())return;n.push({filePath:e,kind:t,size:r.size,mtimeMs:r.mtimeMs})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}}async function dr(e,t,n){let r;try{r=await G.readFile(Bn(e),`utf-8`)}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=JSON.parse(r);return e.version!==1||e.optionsHash!==t||!Array.isArray(e.entries)||!Array.isArray(e.categories)||!Array.isArray(e.manifest)||!pr(e.manifest,n)?void 0:e}catch{return}}async function fr(e,t){if(!await xr(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await G.writeFile(Bn(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function pr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r.filePath!==i.filePath||r.kind!==i.kind||r.size!==i.size||r.mtimeMs!==i.mtimeMs)return!1}return!0}async function mr(e){try{let t=await G.readFile(e,`utf-8`),n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}async function hr(e,t){let n=await G.open(e,`r`);try{let e=await n.stat(),r=Math.min(e.size,t),i=Buffer.alloc(r);return await n.read(i,0,r,0),i.toString(`utf-8`)}finally{await n.close()}}async function gr(e,t){if((await G.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return G.readFile(e,`utf-8`)}function _r(e){let t=He(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
|
|
10
|
+
`)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function vr(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function yr(e){return e.split(K.sep).join(`/`)}function br(e){return e instanceof Error?e.message:String(e)}async function xr(e){try{return await G.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function Sr(e){return Ue(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function Cr(e,t,n,r){let i={"Client-Code":`AIMax`,"X-Session-Id":t};return n&&(i[`X-Message-Id`]=n),r&&(i[`X-Channel`]=r),{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:32768,headers:i,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}const wr=`/aimax/agents`,Tr=/^[a-z]+(?:-[a-z]+)*$/;function Er(e){let t=[{dir:e.systemAgentsDir??wr,source:`system`},{dir:K.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:K.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function Dr(e){let t=new Map;for(let n of Er(e)){let e=await jr(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function Or(e={}){let t=e.allAgents??e.availableAgents??[],n=Fr(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>Nr(n,e),findAny:e=>Nr(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function kr(e){return!!(e&&typeof e==`object`&&Array.isArray(e.allAgents)&&Array.isArray(e.availableAgents)&&typeof e.findPublic==`function`&&typeof e.findAny==`function`&&typeof e.stats==`function`)}async function Ar(e){return kr(e.agentPolicy)?e.agentPolicy:Or({allAgents:await Dr(e)})}async function jr(e,t){let n;try{n=await G.readdir(e,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}let r=[];for(let i of n){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let n=K.join(e,i.name),a=Mr(await G.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function Mr(e,t){let n=He(e),r=Br(n.data.name)?.trim(),i=Br(n.data.description)?.trim();if(!r||!Tr.test(r)||!i)return;let a=Br(n.data.model)?.trim(),o=Br(n.data.initPrompt)?.trim()??Br(n.data.initialPrompt)?.trim(),s=Vr(n.data.maxTurns),c=Hr(n.data.tools),l=Hr(n.data.disallowedTools),u=Hr(n.data.skills),d=Ur(n.data.visibility);if(!(n.data.visibility!==void 0&&!d))return{name:r,description:i,visibility:d??`public`,...c?{tools:c}:{},...l?{disallowedTools:l}:{},...a&&a!==`inherit`?{model:a}:{},...s?{maxTurns:s}:{},...o?{initPrompt:o}:{},...u?{skills:u}:{},systemPrompt:n.content.trim(),sourcePath:t.sourcePath,source:t.source}}function Nr(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Pr(e)===`public`))}function Pr(e){return e.visibility??`public`}function Fr(e){return e.filter(e=>Pr(e)===`public`)}function Ir(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Lr(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Wr)):void 0,r=new Set((t.disallowedTools??[]).map(Wr));return e.filter(e=>{let t=typeof e.name==`string`?Wr(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Rr(e){let t=Fr(e).filter(e=>e.source!==`system`);return t.length===0?``:[`## Custom Agents`,`The following custom agents are currently effective.`,"When delegating with `subagent_spawn`, you may set the optional `agent` field only to one of the exact names listed below.","Do not guess, invent, paraphrase, translate, or synthesize agent names. If no listed custom agent clearly matches, leave `agent` unset and delegate normally.","When the user's message contains `@<agent-name>` (e.g. `@secure-code-reviewer`) and the name exactly matches one of the listed custom agents, that mention is an explicit delegation request.","For such a matching `@<agent-name>` request, you MUST call `subagent_spawn` to run the request through that custom agent, with the `agent` field set to the exact matched agent name.","Do not answer the request yourself, do not merely describe the agent, and do not omit the tool call when a matching `@<agent-name>` is present.",`If the mention does not exactly match a listed custom agent, do not invent a match; continue with the current agent or ask a concise clarification if needed.`,t.map(e=>`- ${e.name}: ${e.description}`).join(`
|
|
11
11
|
`),``].join(`
|
|
12
12
|
`)}function zr(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Br(e){return typeof e==`string`?e:void 0}function Vr(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Hr(e){let t;if(typeof e==`string`)t=e.split(`,`);else if(Array.isArray(e))t=e.filter(e=>typeof e==`string`);else return;let n=t.map(e=>e.trim()).filter(Boolean);return n.length>0?n:void 0}function Ur(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function Wr(e){let t=e.trim();return{bash:`exec`,read:`read_file`,write:`write_file`,edit:`edit_file`,multiedit:`edit_file`,glob:`list_dir`,grep:`exec`}[t.toLowerCase()]??t}const Gr=new qe;async function Kr(e,t){return await Gr.run(e,t)}function qr(e){return{async emit(t){let n=Gr.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}var Jr=class{hooks=new Map;register(e){let t=this.hooks.get(e.hookName)??[];t.push(e),t.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,t)}async dispatch(e,t,n,r){let i=this.hooks.get(e)??[],a=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await Kr({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}},Yr=class{constructor(e){this.params=e}async dispatchProgress(e,t){let n={...t,sessionId:e,...this.params.messageId?{messageId:this.params.messageId}:{},...this.params.subagentContext?{parentSessionId:this.params.subagentContext.parentSessionId,depth:this.params.subagentContext.depth}:{}};await this.params.onProgress?.(n)}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}},Xr=class extends Error{code;statusCode;statusText;providerMessage;providerCode;providerType;retryable;constructor(e){super(e.message,{cause:e.cause}),this.name=`LlmRequestError`,this.code=e.code,this.statusCode=e.statusCode,this.statusText=e.statusText,this.providerMessage=e.providerMessage,this.providerCode=e.providerCode,this.providerType=e.providerType,this.retryable=e.retryable}};function Zr(e){return{async chat(t){let n=Qr(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await ti(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:$r(n),historyMessages:n},e.hookCtx);let i={model:r,messages:n,stream:!1};typeof t.temperature==`number`&&(i.temperature=t.temperature),typeof t.maxTokens==`number`&&(i.max_tokens=t.maxTokens);let{signal:a,clear:o,didTimeout:s}=ni(t.signal,t.timeoutMs);try{let t;try{let n=e.baseUrl.replace(/\/$/,``);t=await fetch(`${n}/chat/completions`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:JSON.stringify(i),signal:a})}catch(e){throw ii(e,s())}if(!t.ok){let e=await ri(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new Xr({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:oi(t.status)})}let n=Date.now(),o;try{o=await t.json()}catch(e){throw new Xr({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}let c=o.choices?.[0]?.message?.content??o.choices?.[0]?.text??``,l=ei(o.usage),u=Math.max(0,Date.now()-n);return await ti(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:c?[c]:[],durationMs:u,usage:l},e.hookCtx),{text:c,usage:l,raw:o}}finally{o()}}}}function Qr(e){if(Array.isArray(e.messages)&&e.messages.length>0)return e.messages;let t=[];if(e.system?.trim()&&t.push({role:`system`,content:e.system}),e.user?.trim()&&t.push({role:`user`,content:e.user}),t.length===0)throw Error(`LLM messages are required`);return t}function $r(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
|
|
13
13
|
`)}function ei(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}async function ti(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function ni(e,t){if(!e&&(!t||t<=0))return{signal:void 0,clear:()=>{},didTimeout:()=>!1};let n=new AbortController,r,i=!1;return e&&(e.aborted?n.abort():e.addEventListener(`abort`,()=>n.abort(),{once:!0})),t&&t>0&&(r=setTimeout(()=>{i=!0,n.abort()},t)),{signal:n.signal,clear:()=>{r&&clearTimeout(r)},didTimeout:()=>i}}async function ri(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function ii(e,t){return e instanceof Xr?e:ai(e)?t?new Xr({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new Xr({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function ai(e){return e instanceof Error&&e.name===`AbortError`}function oi(e){return e===408||e===409||e===425||e===429||e>=500}var si=class extends Error{isHitlPause=!0;constructor(e,t,n,r=!1){super(`HITL_PAUSED`),this.request=e,this.checkpoint=t,this.toolContext=n,this.transparentPause=r,this.name=`HitlPauseSignal`}};function ci(e){return!!(e instanceof si||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}var li=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,outputSchema:i,extra:a,createdAt:new Date().toISOString()}}};function ui(e){return!!(e instanceof li||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const di=new qe;function fi(){return{}}async function pi(e,t){return await di.run(e,t)}function mi(e){let t=di.getStore();!t||t.signal||(t.signal=e)}const hi=new qe;function gi(){return{}}async function _i(e,t){return await hi.run(e,t)}function vi(e){let t=hi.getStore();!t||t.signal||(t.signal=e)}function yi(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function bi(e){if(!yi(e))return null;let t=e,n=xi(t.message),r=Ci(n?.code)??Ci(t.code),i=Ci(n?.type)??Ci(t.type),a=Ci(n?.message)??Si(t.error)??Ci(t.message)??`Unknown upstream error`;return{message:wi(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Ti(r,i),raw:e}}function xi(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return null;try{let e=JSON.parse(t);return e&&typeof e==`object`?e:null}catch{return null}}function Si(e){if(!(!e||typeof e!=`object`))return Ci(e.message)}function Ci(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function wi(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function Ti(e,t){let n=Number(e);if(Number.isFinite(n))return n===408||n===409||n===425||n===429||n>=500;let r=t?.toLowerCase();return r===`ratelimiterror`||r===`internalservererror`}const Ei=(e,t,n)=>{let r=new tt;return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now(),errorMessage:void 0};try{let a=ki(e,t,n?.apiKey||Xe(e.provider)||``,n?.headers),o=Ai(e,t,n);n?.onPayload?.(o);let s=await a.chat.completions.create(o,{signal:n?.signal});r.push({type:`start`,partial:i});let c=null,l=i.content,u=()=>l.length-1,d=e=>{if(e){if(e.type===`text`){r.push({type:`text_end`,contentIndex:u(),content:e.text,partial:i});return}if(e.type===`thinking`){r.push({type:`thinking_end`,contentIndex:u(),content:e.thinking,partial:i});return}e.type===`toolCall`&&(e.arguments=Ze(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=bi(t);if(n)throw new Xr({message:`LLM upstream returned an error payload in a 200 stream: ${n.message}`,code:`stream_payload_error`,providerMessage:n.providerMessage,providerCode:n.providerCode,providerType:n.providerType,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Ye(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=Ii(a.finish_reason)),!a.delta))continue;a.delta.content!==null&&a.delta.content!==void 0&&a.delta.content.length>0&&((!c||c.type!==`text`)&&(d(c),c={type:`text`,text:``},i.content.push(c),r.push({type:`text_start`,contentIndex:u(),partial:i})),c.text+=a.delta.content,r.push({type:`text_delta`,contentIndex:u(),delta:a.delta.content,partial:i}));let o=[`reasoning_content`,`reasoning`,`reasoning_text`].find(e=>{let t=a.delta[e];return t!=null&&t.length>0});if(o){(!c||c.type!==`thinking`)&&(d(c),c={type:`thinking`,thinking:``,thinkingSignature:o},i.content.push(c),r.push({type:`thinking_start`,contentIndex:u(),partial:i}));let e=a.delta[o];c.thinking+=e,r.push({type:`thinking_delta`,contentIndex:u(),delta:e,partial:i})}if(a.delta.tool_calls)for(let e of a.delta.tool_calls){(!c||c.type!==`toolCall`||e.id&&c.id!==e.id)&&(d(c),c={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``},i.content.push(c),r.push({type:`toolcall_start`,contentIndex:u(),partial:i})),e.id&&(c.id=e.id),e.function?.name&&(c.name=e.function.name);let t=``;e.function?.arguments&&(t=e.function.arguments,c.partialArgs+=e.function.arguments,c.arguments=Ze(c.partialArgs)),r.push({type:`toolcall_delta`,contentIndex:u(),delta:t,partial:i})}let s=a.delta.reasoning_details;if(s&&Array.isArray(s)){for(let e of s)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=i.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}if(d(c),n?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(i.errorMessage??(i.stopReason===`aborted`?`Request was aborted`:`LLM stream ended with stopReason=${i.stopReason}`));r.push({type:`done`,reason:i.stopReason,message:i}),r.end()}catch(e){for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`,i.errorMessage=e instanceof Error?e.message:JSON.stringify(e),e instanceof Xr&&Object.assign(i,{errorCode:e.code,statusCode:e.statusCode,statusText:e.statusText,providerMessage:e.providerMessage,providerCode:e.providerCode,providerType:e.providerType,retryable:e.retryable});let t=e?.error?.metadata?.raw;t&&(i.errorMessage+=`\n${t}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},Di=(e,t,n)=>{let r=n?.apiKey||Xe(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=at(e,n,r),a=et(e)?n?.reasoning:ot(n?.reasoning);return Ei(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function Oi(e,t,n){return Ai(e,t,n)}function ki(e,t,n,r){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let i={...e.headers};if(e.provider===`github-copilot`){let e=it(t.messages);Object.assign(i,rt({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new Je({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Ai(e,t,n){let r=Ri(e),i=Pi(e,t,r);Ni(e,i);let a={model:e.id,messages:i,stream:!0};if(r.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),r.supportsStore&&(a.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?a.max_tokens=n.maxTokens:a.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(a.temperature=n.temperature),t.tools?a.tools=Fi(t.tools,r):ji(t.messages)&&(a.tools=[]),n?.toolChoice&&(a.tool_choice=n.toolChoice),(r.thinkingFormat===`zai`||r.thinkingFormat===`qwen`)&&e.reasoning?a.enable_thinking=!!n?.reasoningEffort:n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort&&(a.reasoning_effort=n.reasoningEffort),e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),a.providerOptions={gateway:e}}}return a}function ji(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function Mi(e){let t=e.replace(/[^a-zA-Z0-9]/g,``);return t.length<9?t+=`ABCDEFGHI`.slice(0,9-t.length):t.length>9&&(t=t.slice(0,9)),t}function Ni(e,t){if(!(e.provider!==`openrouter`||!e.id.startsWith(`anthropic/`)))for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.role!==`user`&&n.role!==`assistant`)continue;let r=n.content;if(typeof r==`string`){n.content=[{type:`text`,text:r,cache_control:{type:`ephemeral`}}];return}if(Array.isArray(r))for(let e=r.length-1;e>=0;--e){let t=r[e];if(t?.type===`text`){Object.assign(t,{cache_control:{type:`ephemeral`}});return}}}}function Pi(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return Mi(t);if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=st(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:nt(t.systemPrompt)})}let o=null;for(let t=0;t<a.length;t+=1){let i=a[t];if(n.requiresAssistantAfterToolResult&&o===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`){if(typeof i.content==`string`)r.push({role:`user`,content:nt(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:nt(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}),n=e.input.includes(`image`)?t:t.filter(e=>e.type!==`image_url`);if(n.length===0)continue;r.push({role:`user`,content:n})}o=i.role;continue}if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(e=>e.type===`text`&&e.text?.trim().length>0);a.length>0&&(t.content=e.provider===`github-copilot`?a.map(e=>nt(e.text)).join(``):a.map(e=>({type:`text`,text:nt(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import e from"node:fs/promises";import t from"node:path";import{randomUUID as n}from"node:crypto";async function r(t){try{return await e.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function i(t,n,r){await e.writeFile(t,n,`utf-8`)}async function a(t,n,a){if(!a){await e.appendFile(t,n,`utf-8`);return}let o=await r(t);await i(t,o?o+n:n,!0)}async function o(t,n,r){let i=`${t}.${process.pid}.${Date.now()}.tmp`;await e.writeFile(i,n,`utf-8`),await e.rename(i,t)}async function s(e){return r(e)}const c=`sessions`,l=2e3,u=new Map;function d(e){let t=e?.trim()||c;if(!/^[A-Za-z0-9_-]+$/.test(t))throw Error(`Invalid session store name: ${e}. Must match /^[A-Za-z0-9_-]+$/`);return t}function f(e,t){let n=t.trim();if(!/^[A-Za-z0-9_-]+$/.test(n))throw Error(`Invalid ${e}: ${t}. Must match /^[A-Za-z0-9_-]+$/`);return n}function p(e,n){return t.join(e,`.aimax`,d(n?.storeName))}function m(e,n,r){let i=r?.subagent?f(`subagent session id`,n):n;if(r?.subagent){if(r.subagent.parentDir)return t.join(r.subagent.parentDir,`subagents`,i);let n=f(`parent session id`,r.subagent.parentSessionId);return t.join(p(e,r),n,`subagents`,i)}return t.join(p(e,r),i)}function h(e,n,r){return t.join(m(e,n,r),`transcript.jsonl`)}function g(e,n,r){return t.join(m(e,n,r),`artifacts.json`)}function _(e,n,r){return t.join(m(e,n,r),`session.json`)}function v(e,n,r){return t.join(m(e,n,r),`context.json`)}function y(e,n,r){return t.join(m(e,n,r),`session-memory.json`)}function b(e,n,r){return t.join(m(e,n,r),`collapse-log.jsonl`)}function x(e,n,r){return t.join(m(e,n,r),`tool-results`)}function S(e,n,r){return t.join(m(e,n,r),`cron-executions.jsonl`)}const C={version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}};async function w(r,i,a){let o=a?.sessionId??n(),s=m(r,o,a);await e.mkdir(s,{recursive:!0});let c=t.join(s,`.channel`);return await e.writeFile(c,i,`utf-8`),o}async function T(t,n,r){let i=m(t,n,r);await e.mkdir(i,{recursive:!0})}async function E(e,t,n){let i=await r(h(e,t,n));if(i===null)return[];let a=[];for(let e of i.split(`
|
|
2
2
|
`)){let t=e.trim();if(t)try{a.push(JSON.parse(t))}catch{}}return a}async function D(e,t,n,r){await T(e,t,r);let i=g(e,t,r),a=r?.encryptSessions??!1;await N(i,async()=>{let e=await A(i);await M(i,{version:1,updatedAt:new Date().toISOString(),operations:[...e.operations,k(n)]},a)})}async function O(e,t,n){return(await A(g(e,t,n))).operations}function k(e){let t=e.content.length,n=t>l;return{...e,content:n?`${e.content.slice(0,Math.max(0,l-3))}...`:e.content,timestamp:new Date().toISOString(),truncated:n,originalChars:t}}async function A(e){let t=await r(e);if(t===null)return j();try{let e=JSON.parse(t);return e.version!==1||!Array.isArray(e.operations)?j():{version:1,updatedAt:typeof e.updatedAt==`string`?e.updatedAt:new Date(0).toISOString(),operations:e.operations}}catch{return j()}}function j(){return{version:1,updatedAt:new Date(0).toISOString(),operations:[]}}async function M(n,r,i){await e.mkdir(t.dirname(n),{recursive:!0}),await o(n,`${JSON.stringify(r,null,2)}\n`,i)}async function N(e,t){let n=(u.get(e)??Promise.resolve()).catch(()=>{}).then(t);u.set(e,n);try{await n}finally{u.get(e)===n&&u.delete(e)}}async function P(e,n,r,i){await T(e,n,i);let o=h(e,n,i);await a(o,JSON.stringify(r)+`
|
|
3
|
-
`,i?.encryptSessions??!1);try{let{resolveMemoryProvider:n}=await import(`./provider-registry-Kh5nNG84.js`).then(e=>e.t),{createBuiltinMemoryProvider:r}=await import(`./builtin-provider-
|
|
4
|
-
`),l=a?.encryptSessions??!1;await i(o,c.length>0?`${c}\n`:``,l);try{let{resolveMemoryProvider:n}=await import(`./provider-registry-Kh5nNG84.js`).then(e=>e.t),{createBuiltinMemoryProvider:r}=await import(`./builtin-provider-
|
|
3
|
+
`,i?.encryptSessions??!1);try{let{resolveMemoryProvider:n}=await import(`./provider-registry-Kh5nNG84.js`).then(e=>e.t),{createBuiltinMemoryProvider:r}=await import(`./builtin-provider-Bhzb_o53.js`).then(e=>e.t),a=t.join(e,`.aimax`),s=n({providerId:i?.providerId,pluginId:i?.pluginId,dataDir:e,memoryDir:a,sessionStoreName:i?.storeName})?.provider??r({dataDir:e,memoryDir:a,sessionStoreName:i?.storeName});s.noteSessionUpdate&&s.noteSessionUpdate(o)}catch{}i?.onMemoryChanged&&await Promise.resolve(i.onMemoryChanged({reason:`transcript-append`,files:[t.join(d(i.storeName),n,`transcript.jsonl`).replace(/\\/g,`/`)],source:`sessions`,sessionId:n,providerId:i.providerId??i.pluginId,timestamp:new Date().toISOString()})).catch(()=>{})}async function F(e,n,r,a){await T(e,n,a);let o=h(e,n,a),s=r(await E(e,n,a)),c=s.map(e=>JSON.stringify(e)).join(`
|
|
4
|
+
`),l=a?.encryptSessions??!1;await i(o,c.length>0?`${c}\n`:``,l);try{let{resolveMemoryProvider:n}=await import(`./provider-registry-Kh5nNG84.js`).then(e=>e.t),{createBuiltinMemoryProvider:r}=await import(`./builtin-provider-Bhzb_o53.js`).then(e=>e.t),i=t.join(e,`.aimax`),s=n({providerId:a?.providerId,pluginId:a?.pluginId,dataDir:e,memoryDir:i,sessionStoreName:a?.storeName})?.provider??r({dataDir:e,memoryDir:i,sessionStoreName:a?.storeName});s.noteSessionUpdate&&s.noteSessionUpdate(o)}catch{}return a?.onMemoryChanged&&await Promise.resolve(a.onMemoryChanged({reason:`transcript-rewrite`,files:[t.join(d(a.storeName),n,`transcript.jsonl`).replace(/\\/g,`/`)],source:`sessions`,sessionId:n,providerId:a.providerId??a.pluginId,timestamp:new Date().toISOString()})).catch(()=>{}),s}async function I(e,t,n,r){await T(e,t,r),await a(S(e,t,r),JSON.stringify(n)+`
|
|
5
5
|
`,r?.encryptSessions??!1)}async function L(e,t,n){let i=await r(S(e,t,n));if(i===null)return[];let a=[];for(let e of i.split(`
|
|
6
6
|
`)){let t=e.trim();if(t)try{a.push(JSON.parse(t))}catch{}}return a}async function R(t,n){let r=p(t,n);try{return(await e.readdir(r,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function z(e,t,n){await T(e,t.id,n);let r=_(e,t.id,n),a=n?.encryptSessions??!1;await i(r,JSON.stringify(t,null,2),a)}async function B(e,t,n,r){let i=await V(e,t,r);if(!i)return null;let a={...i,...n,id:i.id,createdAt:i.createdAt,updatedAt:new Date().toISOString()};return await z(e,a,r),a}async function V(n,i,a){let o=await r(_(n,i,a));if(o===null)return null;try{let r=JSON.parse(o);if(!r.channel){let o=t.join(m(n,i,a),`.channel`);try{r.channel=(await e.readFile(o,`utf-8`)).trim()}catch{r.channel=`WEB`}}return r}catch{return null}}async function H(e,t,n){let r=await R(e,n),i=await Promise.all(r.map(async t=>{let r=await V(e,t,n);return{id:t,title:r?.title??t,channel:r?.channel??`WEB`,createdAt:r?.createdAt??``,updatedAt:r?.updatedAt??``}}));return t?i.filter(e=>e.channel===t):i}async function U(e,t,n){let i=await r(v(e,t,n));if(i===null)return C;try{let e=JSON.parse(i),t=typeof e.version==`number`?e.version:void 0;return t!==1&&t!==2?C:{version:2,updatedAt:typeof e.updatedAt==`string`?e.updatedAt:C.updatedAt,readStates:Array.isArray(e.readStates)?e.readStates:[],toolResults:Array.isArray(e.toolResults)?e.toolResults:[],compaction:{sessionMemory:e.compaction?.sessionMemory,modelUsage:e.compaction?.modelUsage,budgets:Array.isArray(e.compaction?.budgets)?e.compaction.budgets:[],snips:Array.isArray(e.compaction?.snips)?e.compaction.snips:[],collapseSpans:Array.isArray(e.compaction?.collapseSpans)?e.compaction.collapseSpans:[],consecutiveAutocompactFailures:typeof e.compaction?.consecutiveAutocompactFailures==`number`?e.compaction.consecutiveAutocompactFailures:0,lastCompactionAt:typeof e.compaction?.lastCompactionAt==`string`?e.compaction.lastCompactionAt:void 0,lastCompactionLayer:e.compaction?.lastCompactionLayer===`L1`||e.compaction?.lastCompactionLayer===`L2`||e.compaction?.lastCompactionLayer===`L3`||e.compaction?.lastCompactionLayer===`L4`||e.compaction?.lastCompactionLayer===`L5`||e.compaction?.lastCompactionLayer===`L6`?e.compaction.lastCompactionLayer:void 0}}}catch{return C}}async function W(t,n,r){let i=m(t,n,r);try{return(await e.stat(i)).isDirectory()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function G(e,t,n){let[r,i,a]=await Promise.all([V(e,t,n),E(e,t,n),U(e,t,n)]);return{id:t,metadata:r,transcriptPath:h(e,t,n),contextSnapshotPath:v(e,t,n),sessionMemoryPath:y(e,t,n),collapseLogPath:b(e,t,n),toolResultsDir:x(e,t,n),transcriptEntryCount:i.length,readStateCount:a.readStates.length,toolResultRefCount:a.toolResults.length,transcriptEntries:i,context:a}}async function K(e,t,n){let r=await G(e,t,n);return{id:r.id,metadata:r.metadata,transcript:r.transcriptEntries,context:r.context,paths:{transcriptPath:r.transcriptPath,contextSnapshotPath:r.contextSnapshotPath,sessionMemoryPath:r.sessionMemoryPath,collapseLogPath:r.collapseLogPath,toolResultsDir:r.toolResultsDir}}}export{h as A,F as C,y as D,W as E,s as F,i as I,a as M,o as N,p as O,r as P,d as S,m as T,L as _,P as a,E as b,v as c,T as d,K as f,O as g,R as h,I as i,B as j,x as k,w as l,H as m,l as n,g as o,G as p,D as r,b as s,c as t,S as u,U as v,z as w,_ as x,V as y};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{I as t,M as n,P as r,T as i}from"./session-
|
|
1
|
+
import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{I as t,M as n,P as r,T as i}from"./session-CiekMEUQ.js";import a from"node:fs/promises";import o from"node:path";var s=e({appendHitlHistory:()=>d,clearPendingHitl:()=>_,createPendingHitl:()=>m,findResolvedHitlState:()=>g,hitlHistoryPath:()=>l,pendingHitlPath:()=>c,readHitlHistory:()=>p,readPendingHitl:()=>f,transitionHitlStatus:()=>h,writePendingHitl:()=>u});function c(e,t,n){return o.join(i(e,t,n),`pending-hitl.json`)}function l(e,t,n){return o.join(i(e,t,n),`hitl-history.jsonl`)}async function u(e,n,r,o){let s=i(e,n,o);await a.mkdir(s,{recursive:!0});let l=c(e,n,o),u=o?.encryptSessions??!1;await t(l,JSON.stringify(r,null,2),u)}async function d(e,t,r,o){let s=i(e,t,o);await a.mkdir(s,{recursive:!0}),await n(l(e,t,o),JSON.stringify(r)+`
|
|
2
2
|
`,o?.encryptSessions??!1)}async function f(e,t,n){let i=await r(c(e,t,n));if(i===null)return null;try{return JSON.parse(i)}catch{return null}}async function p(e,t,n){let i=await r(l(e,t,n));if(i===null)return[];let a=[];for(let e of i.split(`
|
|
3
3
|
`)){let t=e.trim();if(t)try{a.push(JSON.parse(t))}catch{}}return a}async function m(e,t,n,r,i,a,o){let s=new Date().toISOString(),c={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:s,updatedAt:s};return await u(e,t,c,o),await d(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function h(e,t,n,r,i,a){let o=await f(e,t,a);if(!o||o.request.requestId!==n||o.status!==`pending`)return null;let s=new Date().toISOString(),c={...o,status:r,resolution:i,updatedAt:s};await u(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await d(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function g(e,t,n,r){let i=await f(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function _(e,t,n){let r=c(e,t,n);try{await a.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}export{c as a,s as c,l as i,h as l,m as n,p as o,g as r,f as s,_ as t};
|
package/package.json
CHANGED
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{O as t,P as n,S as r}from"./session-BDGOSbwC.js";import{createRequire as i}from"node:module";import a from"node:fs/promises";import o,{basename as s}from"node:path";import c from"node:crypto";import l from"node:fs";function u(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}async function d(e){let t;try{t=await a.lstat(e)}catch(e){if(u(e))return{missing:!0};throw e}if(t.isSymbolicLink()||!t.isFile())throw Error(`path required`);return{missing:!1,stat:t}}function f(e){try{l.mkdirSync(e,{recursive:!0})}catch{}return e}function p(e){return e.trim().replace(/^[./]+/,``).replace(/\\/g,`/`)}function m(e){let t=p(e);return t?t===`MEMORY.md`||t===`memory.md`?!0:t.startsWith(`memory/`):!1}async function h(e,t){let n=await a.readdir(e,{withFileTypes:!0});for(let r of n){let n=o.join(e,r.name);if(!r.isSymbolicLink()){if(r.isDirectory()){await h(n,t);continue}r.isFile()&&r.name.endsWith(`.md`)&&t.push(n)}}}async function g(e){let t=[],n=o.join(e,`MEMORY.md`),r=o.join(e,`memory.md`),i=o.join(e,`memory`),s=async e=>{try{let n=await a.lstat(e);if(n.isSymbolicLink()||!n.isFile()||!e.endsWith(`.md`))return;t.push(e)}catch{}};await s(n),await s(r);try{let e=await a.lstat(i);!e.isSymbolicLink()&&e.isDirectory()&&await h(i,t)}catch{}if(t.length<=1)return t;let c=new Set,l=[];for(let e of t){let t=e;try{t=await a.realpath(e)}catch{}c.has(t)||(c.add(t),l.push(e))}return l}function _(e){return c.createHash(`sha256`).update(e).digest(`hex`)}async function v(e,t){let n;try{n=await a.stat(e)}catch(e){if(u(e))return null;throw e}let r;try{r=await a.readFile(e,`utf-8`)}catch(e){if(u(e))return null;throw e}let i=_(r);return{path:o.relative(t,e).replace(/\\/g,`/`),absPath:e,mtimeMs:n.mtimeMs,size:n.size,hash:i}}function y(e,t){let n=e.split(`
|
|
2
|
-
`);if(n.length===0)return[];let r=Math.max(32,t.tokens*4),i=Math.max(0,t.overlap*4),a=[],o=[],s=0,c=()=>{if(o.length===0)return;let e=o[0],t=o[o.length-1];if(!e||!t)return;let n=o.map(e=>e.line).join(`
|
|
3
|
-
`),r=e.lineNo,i=t.lineNo;a.push({startLine:r,endLine:i,text:n,hash:_(n)})},l=()=>{if(i<=0||o.length===0){o=[],s=0;return}let e=0,t=[];for(let n=o.length-1;n>=0;--n){let r=o[n];if(r&&(e+=r.line.length+1,t.unshift(r),e>=i))break}o=t,s=t.reduce((e,t)=>e+t.line.length+1,0)};for(let e=0;e<n.length;e+=1){let t=n[e]??``,i=e+1,a=[];if(t.length===0)a.push(``);else for(let e=0;e<t.length;e+=r)a.push(t.slice(e,e+r));for(let e of a){let t=e.length+1;s+t>r&&o.length>0&&(c(),l()),o.push({line:e,lineNo:i}),s+=t}}return c(),a}function ee(e,t){if(!(!t||t.length===0))for(let n of e)n.startLine=t[n.startLine-1]??n.startLine,n.endLine=t[n.endLine-1]??n.endLine}function b(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function te(e,t){if(e.length===0||t.length===0)return 0;let n=Math.min(e.length,t.length),r=0,i=0,a=0;for(let o=0;o<n;o+=1){let n=e[o]??0,s=t[o]??0;r+=n*s,i+=n*n,a+=s*s}return i===0||a===0?0:r/(Math.sqrt(i)*Math.sqrt(a))}function ne(e){return(e.toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[]).filter(Boolean)}function re(e){return c.createHash(`sha256`).update(e).digest().readUInt32BE(0)}function x(e,t=384){let n=Array(t).fill(0),r=ne(e);if(r.length===0)return n;for(let e of r){let r=re(e)%t;n[r]+=1}let i=Math.sqrt(n.reduce((e,t)=>e+t*t,0));if(i>0)for(let e=0;e<n.length;e+=1)n[e]=n[e]/i;return n}function S(e){let t=e?.model?.trim()||`mock-embedding-v1`,n=e?.dimensions??384;return{id:`external-mock`,model:t,embedQuery:async e=>x(e,n),embedBatch:async e=>e.map(e=>x(e,n))}}const C=new class{providers=new Map;byPluginId=new Map;register(e){this.providers.set(e.id,e),e.pluginId&&this.byPluginId.set(e.pluginId,e.id)}getById(e){return this.providers.get(e)}getByPluginId(e){let t=this.byPluginId.get(e);return t?this.providers.get(t):void 0}clear(){this.providers.clear(),this.byPluginId.clear()}};function ie(e){let t=e.id?.trim()||e.pluginId;return C.register({id:t,pluginId:e.pluginId,create:e.create,config:e.config,rootDir:e.rootDir,source:e.source}),t}function w(e){let t=e.providerId?.trim(),n=e.pluginId?.trim(),r=(t?C.getById(t):void 0)??(n?C.getByPluginId(n):void 0);return r?{provider:r.create({dataDir:e.dataDir,memoryDir:e.memoryDir,pluginId:r.pluginId,config:r.config,rootDir:r.rootDir,source:r.source}),registration:r}:null}function ae(){C.clear()}const T={enabled:!1,lambda:.7};function E(e){let t=e.toLowerCase().match(/[a-z0-9_]+/g)??[];return new Set(t)}function oe(e,t){if(e.size===0&&t.size===0)return 1;if(e.size===0||t.size===0)return 0;let n=0,r=e.size<=t.size?e:t,i=e.size<=t.size?t:e;for(let e of r)i.has(e)&&n++;let a=e.size+t.size-n;return a===0?0:n/a}function se(e,t,n){if(t.length===0)return 0;let r=0,i=n.get(e.id)??E(e.content);for(let e of t){let t=oe(i,n.get(e.id)??E(e.content));t>r&&(r=t)}return r}function ce(e,t,n){return n*e-(1-n)*t}function le(e,t={}){let{enabled:n=T.enabled,lambda:r=T.lambda}=t;if(!n||e.length<=1)return[...e];let i=Math.max(0,Math.min(1,r));if(i===1)return e.slice().sort((e,t)=>t.score-e.score);let a=new Map;for(let t of e)a.set(t.id,E(t.content));let o=Math.max(...e.map(e=>e.score)),s=Math.min(...e.map(e=>e.score)),c=o-s,l=e=>c===0?1:(e-s)/c,u=[],d=new Set(e);for(;d.size>0;){let e=null,t=-1/0;for(let n of d){let r=ce(l(n.score),se(n,u,a),i);(r>t||r===t&&n.score>(e?.score??-1/0))&&(t=r,e=n)}if(e)u.push(e),d.delete(e);else break}return u}function ue(e,t={}){if(e.length===0)return e;let n=new Map;return le(e.map((e,t)=>{let r=`${e.path}:${e.startLine}:${t}`;return n.set(r,e),{id:r,score:e.score,content:e.snippet}}),t).map(e=>n.get(e.id))}const D={enabled:!1,halfLifeDays:30},O=/(?:^|\/)(?:memory)\/(\d{4})-(\d{2})-(\d{2})\.md$/;function de(e){return!Number.isFinite(e)||e<=0?0:Math.LN2/e}function k(e){let t=de(e.halfLifeDays),n=Math.max(0,e.ageInDays);return t<=0||!Number.isFinite(n)?1:Math.exp(-t*n)}function A(e){return e.score*k(e)}function j(e){let t=e.replaceAll(`\\`,`/`).replace(/^\.\//,``),n=O.exec(t);if(!n)return null;let r=Number(n[1]),i=Number(n[2]),a=Number(n[3]);if(!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(a))return null;let o=Date.UTC(r,i-1,a),s=new Date(o);return s.getUTCFullYear()!==r||s.getUTCMonth()!==i-1||s.getUTCDate()!==a?null:s}function M(e){let t=e.replaceAll(`\\`,`/`).replace(/^\.\//,``);return t===`MEMORY.md`||t===`memory.md`?!0:t.startsWith(`memory/`)?!O.test(t):!1}async function N(e){let t=j(e.filePath);if(t)return t;if(e.source===`memory`&&M(e.filePath)||!e.memoryRoot)return null;let n=o.isAbsolute(e.filePath)?e.filePath:o.resolve(e.memoryRoot,e.filePath);try{let e=await a.stat(n);return Number.isFinite(e.mtimeMs)?new Date(e.mtimeMs):null}catch{return null}}function P(e,t){return Math.max(0,t-e.getTime())/864e5}async function F(e){let t={...D,...e.temporalDecay};if(!t.enabled)return[...e.results];let n=e.nowMs??Date.now(),r=new Map;return Promise.all(e.results.map(async i=>{let a=`${i.source}:${i.path}`,o=r.get(a);o||(o=N({filePath:i.path,source:i.source,memoryRoot:e.memoryRoot}),r.set(a,o));let s=await o;if(!s)return i;let c=A({score:i.score,ageInDays:P(s,n),halfLifeDays:t.halfLifeDays});return{...i,score:c}}))}function I(e){let t=e.match(/[\p{L}\p{N}_]+/gu)?.map(e=>e.trim()).filter(Boolean)??[];return t.length===0?null:t.map(e=>`"${e.replaceAll(`"`,``)}"`).join(` AND `)}function L(e){return 1/(1+(Number.isFinite(e)?Math.max(0,e):999))}async function R(e){let t=new Map;for(let n of e.vector)t.set(n.id,{id:n.id,path:n.path,startLine:n.startLine,endLine:n.endLine,source:n.source,snippet:n.snippet,vectorScore:n.vectorScore,textScore:0});for(let n of e.keyword){let e=t.get(n.id);e?(e.textScore=n.textScore,n.snippet&&n.snippet.length>0&&(e.snippet=n.snippet)):t.set(n.id,{id:n.id,path:n.path,startLine:n.startLine,endLine:n.endLine,source:n.source,snippet:n.snippet,vectorScore:0,textScore:n.textScore})}let n=(await F({results:Array.from(t.values()).map(t=>{let n=e.vectorWeight*t.vectorScore+e.textWeight*t.textScore;return{path:t.path,startLine:t.startLine,endLine:t.endLine,score:n,snippet:t.snippet,source:t.source}}),temporalDecay:{...D,...e.temporalDecay},memoryRoot:e.memoryRoot,nowMs:e.nowMs})).slice().sort((e,t)=>t.score-e.score),r={...T,...e.mmr};return r.enabled?ue(n,r):n}function z(e){e.db.exec(`
|
|
4
|
-
CREATE TABLE IF NOT EXISTS meta (
|
|
5
|
-
key TEXT PRIMARY KEY,
|
|
6
|
-
value TEXT NOT NULL
|
|
7
|
-
);
|
|
8
|
-
`),e.db.exec(`
|
|
9
|
-
CREATE TABLE IF NOT EXISTS files (
|
|
10
|
-
path TEXT PRIMARY KEY,
|
|
11
|
-
source TEXT NOT NULL DEFAULT 'memory',
|
|
12
|
-
hash TEXT NOT NULL,
|
|
13
|
-
mtime INTEGER NOT NULL,
|
|
14
|
-
size INTEGER NOT NULL
|
|
15
|
-
);
|
|
16
|
-
`),e.db.exec(`
|
|
17
|
-
CREATE TABLE IF NOT EXISTS chunks (
|
|
18
|
-
id TEXT PRIMARY KEY,
|
|
19
|
-
path TEXT NOT NULL,
|
|
20
|
-
source TEXT NOT NULL DEFAULT 'memory',
|
|
21
|
-
start_line INTEGER NOT NULL,
|
|
22
|
-
end_line INTEGER NOT NULL,
|
|
23
|
-
hash TEXT NOT NULL,
|
|
24
|
-
model TEXT NOT NULL,
|
|
25
|
-
text TEXT NOT NULL,
|
|
26
|
-
embedding TEXT NOT NULL,
|
|
27
|
-
updated_at INTEGER NOT NULL
|
|
28
|
-
);
|
|
29
|
-
`),e.db.exec(`
|
|
30
|
-
CREATE TABLE IF NOT EXISTS ${e.embeddingCacheTable} (
|
|
31
|
-
provider TEXT NOT NULL,
|
|
32
|
-
model TEXT NOT NULL,
|
|
33
|
-
provider_key TEXT NOT NULL,
|
|
34
|
-
hash TEXT NOT NULL,
|
|
35
|
-
embedding TEXT NOT NULL,
|
|
36
|
-
dims INTEGER,
|
|
37
|
-
updated_at INTEGER NOT NULL,
|
|
38
|
-
PRIMARY KEY (provider, model, provider_key, hash)
|
|
39
|
-
);
|
|
40
|
-
`),e.db.exec(`CREATE INDEX IF NOT EXISTS idx_embedding_cache_updated_at ON ${e.embeddingCacheTable}(updated_at);`);let t=!1,n;if(e.ftsEnabled)try{e.db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.ftsTable} USING fts5(\n text,\n id UNINDEXED,\n path UNINDEXED,\n source UNINDEXED,\n model UNINDEXED,\n start_line UNINDEXED,\n end_line UNINDEXED\n);`),t=!0}catch(e){let r=e instanceof Error?e.message:String(e);t=!1,n=r}return B(e.db,`files`,`source`,`TEXT NOT NULL DEFAULT 'memory'`),B(e.db,`chunks`,`source`,`TEXT NOT NULL DEFAULT 'memory'`),e.db.exec(`CREATE INDEX IF NOT EXISTS idx_chunks_path ON chunks(path);`),e.db.exec(`CREATE INDEX IF NOT EXISTS idx_chunks_source ON chunks(source);`),{ftsAvailable:t,...n?{ftsError:n}:{}}}function B(e,t,n,r){e.prepare(`PRAGMA table_info(${t})`).all().some(e=>e.name===n)||e.exec(`ALTER TABLE ${t} ADD COLUMN ${n} ${r}`)}function V(e,t){return e.length<=t?e:e.slice(0,t)}const H=e=>Buffer.from(new Float32Array(e).buffer);async function U(e){return e.queryVec.length===0||e.limit<=0?[]:await e.ensureVectorReady(e.queryVec.length)?e.db.prepare(`SELECT c.id, c.path, c.start_line, c.end_line, c.text,
|
|
41
|
-
c.source,
|
|
42
|
-
vec_distance_cosine(v.embedding, ?) AS dist
|
|
43
|
-
FROM ${e.vectorTable} v\n JOIN chunks c ON c.id = v.id\n WHERE c.model = ?${e.sourceFilterVec.sql}\n ORDER BY dist ASC\n LIMIT ?`).all(H(e.queryVec),e.providerModel,...e.sourceFilterVec.params,e.limit).map(t=>({id:t.id,path:t.path,startLine:t.start_line,endLine:t.end_line,score:1-t.dist,snippet:V(t.text,e.snippetMaxChars),source:t.source})):fe({db:e.db,providerModel:e.providerModel,sourceFilter:e.sourceFilterChunks}).map(t=>({chunk:t,score:te(e.queryVec,t.embedding)})).filter(e=>Number.isFinite(e.score)).slice().sort((e,t)=>t.score-e.score).slice(0,e.limit).map(t=>({id:t.chunk.id,path:t.chunk.path,startLine:t.chunk.startLine,endLine:t.chunk.endLine,score:t.score,snippet:V(t.chunk.text,e.snippetMaxChars),source:t.chunk.source}))}function fe(e){return e.db.prepare(`SELECT id, path, start_line, end_line, text, embedding, source
|
|
44
|
-
FROM chunks
|
|
45
|
-
WHERE model = ?${e.sourceFilter.sql}`).all(e.providerModel,...e.sourceFilter.params).map(e=>({id:e.id,path:e.path,startLine:e.start_line,endLine:e.end_line,text:e.text,embedding:b(e.embedding),source:e.source}))}async function pe(e){if(e.limit<=0)return[];let t=e.buildFtsQuery(e.query);if(!t)return[];let n=e.providerModel?` AND model = ?`:``,r=e.providerModel?[e.providerModel]:[];return e.db.prepare(`SELECT id, path, source, start_line, end_line, text,\n bm25(${e.ftsTable}) AS rank\n FROM ${e.ftsTable}\n WHERE ${e.ftsTable} MATCH ?${n}${e.sourceFilter.sql}\n ORDER BY rank ASC\n LIMIT ?`).all(t,...r,...e.sourceFilter.params,e.limit).map(t=>{let n=e.bm25RankToScore(t.rank);return{id:t.id,path:t.path,startLine:t.start_line,endLine:t.end_line,score:n,textScore:n,snippet:V(t.text,e.snippetMaxChars),source:t.source}})}const me=i(import.meta.url);function he(){try{return me(`node:sqlite`)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`SQLite support is unavailable in this Node runtime (missing node:sqlite). ${t}`,{cause:e})}}const W={chunkTokens:400,chunkOverlap:80,maxResults:6,minScore:.2,fallback:{enabled:!0},embedding:{},experimental:{sessionMemory:!1},sources:[`memory`],store:{sessionStoreName:void 0,vector:{enabled:!0}},hybrid:{enabled:!0,vectorWeight:.7,textWeight:.3,candidateMultiplier:4,mmr:{enabled:!1,lambda:.7},temporalDecay:{enabled:!1,halfLifeDays:30}},cache:{enabled:!0,maxEntries:5e4},sync:{onSessionStart:!0,onSearch:!0,watch:!0,watchDebounceMs:1500,sessions:{deltaBytes:1e5,deltaMessages:50}},citations:`auto`};async function ge(e){try{let t=await import(`sqlite-vec`),n=e.extensionPath?.trim()?e.extensionPath.trim():void 0,r=n??t.getLoadablePath();return n?e.db.loadExtension(r):t.load(e.db),{ok:!0,extensionPath:r}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function _e(e,n,r){let i=t(e,{storeName:r});return o.relative(i,n).replace(/\\/g,`/`)}async function ve(e,n){let r=t(e,{storeName:n});try{let e=await a.readdir(r,{withFileTypes:!0}),t=[];for(let n of e){if(!n.isDirectory())continue;let e=o.join(r,n.name,`transcript.jsonl`);try{(await a.stat(e)).isFile()&&t.push(e)}catch{}}return t}catch(e){if(u(e))return[];throw e}}function ye(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e==`string`?e:e&&typeof e==`object`&&`text`in e?String(e.text??``):``).filter(Boolean).join(` `):e?String(e):``}async function be(e,t,i){let s;try{s=await a.stat(t)}catch(e){if(u(e))return null;throw e}let c;try{let e=await n(t);if(e===null)return null;c=e}catch(e){if(u(e))return null;throw e}let l=[],d=[],f=c.split(`
|
|
46
|
-
`);for(let e=0;e<f.length;e+=1){let t=f[e]?.trim();if(t)try{let n=JSON.parse(t),r=n.role??`unknown`,i=ye(n.content);if(!i)continue;let a=i.split(`
|
|
47
|
-
`);for(let t of a)l.push(`[${r}] ${t}`),d.push(e+1)}catch{}}let p=l.join(`
|
|
48
|
-
`),m=_(p);return{path:o.join(r(i),_e(e,t,i)).replace(/\\/g,`/`),absPath:t,mtimeMs:s.mtimeMs,size:s.size,hash:m,content:p,lineMap:d}}const G=`chunks_vec`,K=`chunks_fts`,q=`embedding_cache`,J=`memory_index_meta_v1`,Y=3e4;function xe(e,t,n){let r=t.split(`
|
|
49
|
-
`);for(let t of r){let n=t.match(/^##\s+(.+)$/);if(n?.[1])return`${e}#${n[1].trim()}`}return`${e}#L${n}`}const X=new Map;function Z(e,t){let n={...e,...t,hybrid:{...e.hybrid,...t?.hybrid??{}},cache:{...e.cache,...t?.cache??{}},sync:{...e.sync,...t?.sync??{}},experimental:{...e.experimental,...t?.experimental??{}},sources:t?.sources??e.sources,embedding:{...e.embedding,...t?.embedding??{}},store:{...e.store,...t?.store??{},vector:{...e.store.vector,...t?.store?.vector??{}}}};return n.experimental.sessionMemory&&!n.sources.includes(`sessions`)&&(n.sources=[...n.sources,`sessions`]),n}var Q=class e{dataDir;memoryRoot;storePath;config;sessionStoreName;provider;providerKey;embeddingProviderId;db;dirty=!0;ftsAvailable=!1;ftsError;vector={enabled:!0,available:null,extensionPath:void 0,loadError:void 0,dims:void 0};vectorReady=null;watchers=[];watchTimer=null;sessionWatchTimer=null;sessionsDirty=!1;sessionsDirtyFiles=new Set;sessionPendingFiles=new Set;searchFallbackOnly=!1;lastRebuildSummary;sessionDeltas=new Map;static get(t,n){let i=o.join(t,`.aimax`),a=Z(W,n),s=`${i}::${r(a.store.sessionStoreName)}`,c=X.get(s);if(c)return n&&c.applyConfig(n),c;let l=new e(t,i,a);return X.set(s,l),l}constructor(e,t,n){this.dataDir=e,this.memoryRoot=t,this.storePath=o.join(t,`.index.sqlite`),this.config=Z(W,n),this.sessionStoreName=r(this.config.store.sessionStoreName),this.provider=S(),this.providerKey=this.computeProviderKey(),this.applyEmbeddingProvider(),this.vector.enabled=this.config.store.vector.enabled,this.vector.extensionPath=this.config.store.vector.extensionPath,this.db=this.openDatabase(),this.ensureSchema(),this.ensureWatcher(),this.ensureSessionListener(),this.dirty=!0}applyConfig(e){this.config=Z(this.config,e),this.sessionStoreName=r(this.config.store.sessionStoreName),this.applyEmbeddingProvider(),this.vector.enabled=this.config.store.vector.enabled,this.vector.extensionPath=this.config.store.vector.extensionPath,this.ensureWatcher(),this.ensureSessionListener()}warmSession(){this.config.sync.onSessionStart&&this.sync({reason:`session-start`}).catch(()=>{})}noteSessionUpdate(e){this.scheduleSessionDirty(e)}status(){let e=this.buildSourceFilter(),t=this.db.prepare(`SELECT COUNT(*) as c FROM files WHERE 1=1${e.sql}`).get(...e.params),n=this.db.prepare(`SELECT COUNT(*) as c FROM chunks WHERE 1=1${e.sql}`).get(...e.params),r=(()=>{let t=Array.from(this.config.sources);if(t.length===0)return[];let n=new Map;for(let e of t)n.set(e,{files:0,chunks:0});let r=this.db.prepare(`SELECT source, COUNT(*) as c FROM files WHERE 1=1${e.sql} GROUP BY source`).all(...e.params);for(let e of r){let t=n.get(e.source)??{files:0,chunks:0};t.files=e.c??0,n.set(e.source,t)}let i=this.db.prepare(`SELECT source, COUNT(*) as c FROM chunks WHERE 1=1${e.sql} GROUP BY source`).all(...e.params);for(let e of i){let t=n.get(e.source)??{files:0,chunks:0};t.chunks=e.c??0,n.set(e.source,t)}return t.map(e=>Object.assign({source:e},n.get(e)))})(),i=this.provider?`hybrid`:`fts-only`,a=this.config.cache.enabled?this.db.prepare(`SELECT COUNT(*) as c FROM ${q}`).get()?.c??0:void 0;return{backend:`builtin`,files:t?.c??0,chunks:n?.c??0,dirty:this.dirty||this.sessionsDirty,workspaceDir:this.memoryRoot,dbPath:this.storePath,provider:this.provider.id,model:this.provider.model,sources:Array.from(this.config.sources),sourceCounts:r,cache:this.config.cache.enabled?{enabled:!0,entries:a,maxEntries:this.config.cache.maxEntries}:{enabled:!1,maxEntries:this.config.cache.maxEntries},fts:{enabled:this.config.hybrid.enabled,available:this.ftsAvailable,error:this.ftsError,rows:this.getFtsRowCount()},vector:{enabled:this.vector.enabled,available:this.vector.available??void 0,extensionPath:this.vector.extensionPath,loadError:this.vector.loadError,dims:this.vector.dims},custom:{searchMode:i,fallbackActive:this.searchFallbackOnly,lastRebuildSummary:this.lastRebuildSummary}}}async probeEmbeddingAvailability(){try{return await this.provider.embedBatch([`ping`]),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async probeVectorAvailability(){return this.vector.enabled?await this.ensureVectorReady():!1}async search(e){let t=e.trim();if(!t)return[];if(this.readMeta()?this.config.sync.onSearch&&(this.dirty||this.sessionsDirty)&&this.sync({reason:`search`}).catch(()=>{this.searchFallbackOnly=!0}):await this.sync({reason:`boot`}).catch(()=>{this.searchFallbackOnly=!0}),this.searchFallbackOnly)return this.decorateCitations(await this.fileScanSearch(t));let n=this.config.hybrid,r=Math.min(200,Math.max(1,Math.floor(this.config.maxResults*n.candidateMultiplier))),i=n.enabled&&this.ftsAvailable?await this.searchKeyword(t,r).catch(()=>[]):[],a=await this.provider.embedQuery(t).catch(()=>[]),o=a.some(e=>e!==0)?await this.searchVector(a,r).catch(()=>[]):[],s=[];if(!n.enabled||!this.ftsAvailable)s=o.filter(e=>e.score>=this.config.minScore).slice(0,this.config.maxResults);else{let e=await R({vector:o.map(e=>({id:`${e.path}:${e.startLine}:${e.endLine}:${e.source}`,path:e.path,startLine:e.startLine,endLine:e.endLine,source:e.source,snippet:e.snippet,vectorScore:e.score})),keyword:i.map(e=>({id:`${e.path}:${e.startLine}:${e.endLine}:${e.source}`,path:e.path,startLine:e.startLine,endLine:e.endLine,source:e.source,snippet:e.snippet,textScore:e.textScore})),vectorWeight:n.vectorWeight,textWeight:n.textWeight,mmr:n.mmr,temporalDecay:n.temporalDecay,memoryRoot:this.memoryRoot}),t=e.filter(e=>e.score>=this.config.minScore);if(t.length>0||i.length===0)s=t.slice(0,this.config.maxResults);else{let t=Math.min(this.config.minScore,n.textWeight);s=e.filter(e=>e.score>=t).slice(0,this.config.maxResults)}}return s.length>0?this.decorateCitations(this.decorateEntryIds(s)):this.config.fallback.enabled?(this.searchFallbackOnly=!0,this.decorateCitations(this.decorateEntryIds(await this.fileScanSearch(t)))):[]}async readFile(e){let{absPath:t,relPath:n}=this.resolveMemoryFilePath(e.relPath);if((await d(t)).missing)return{text:``,path:n};let r;try{r=await a.readFile(t,`utf-8`)}catch(e){if(u(e))return{text:``,path:n};throw e}if(!e.from&&!e.lines)return{text:r,path:n};let i=r.split(`
|
|
50
|
-
`),o=Math.max(1,e.from??1),s=Math.max(1,e.lines??i.length);return{text:i.slice(o-1,o-1+s).join(`
|
|
51
|
-
`),path:n}}async replaceFile(e){let{absPath:t}=this.resolveMemoryFilePath(e.relPath);await a.mkdir(o.dirname(t),{recursive:!0}),await a.writeFile(t,e.content,`utf-8`),this.dirty=!0,await this.syncAndPostCheck(`replace`)}async deleteFile(e){let{absPath:t}=this.resolveMemoryFilePath(e);try{await a.unlink(t)}catch(e){if(u(e))return;throw e}this.dirty=!0,await this.syncAndPostCheck(`delete`)}async appendToMemory(e){let t=this.memoryRoot;await a.mkdir(t,{recursive:!0});let n=o.join(t,`MEMORY.md`),r=e.endsWith(`
|
|
52
|
-
`)?e:`${e}\n`;await a.appendFile(n,r,`utf-8`),this.dirty=!0,await this.syncAndPostCheck(`append`)}openDatabase(){f(o.dirname(this.storePath));let{DatabaseSync:e}=he();return new e(this.storePath,{allowExtension:this.vector.enabled})}ensureSchema(){let e=z({db:this.db,embeddingCacheTable:q,ftsTable:K,ftsEnabled:this.config.hybrid.enabled});this.ftsAvailable=e.ftsAvailable,e.ftsError&&(this.ftsError=e.ftsError)}async ensureVectorReady(e){if(!this.vector.enabled)return!1;this.vectorReady||=this.withTimeout(this.loadVectorExtension(),Y,`sqlite-vec load timed out after ${Math.round(Y/1e3)}s`);let t=!1;try{t=await this.vectorReady||!1}catch(e){let t=e instanceof Error?e.message:String(e);return this.vector.available=!1,this.vector.loadError=t,this.vectorReady=null,!1}return t&&typeof e==`number`&&e>0&&this.ensureVectorTable(e),t}async loadVectorExtension(){if(this.vector.available!==null)return this.vector.available;if(!this.vector.enabled)return this.vector.available=!1,!1;try{let e=this.vector.extensionPath?.trim()?this.vector.extensionPath.trim():void 0,t=await ge({db:this.db,extensionPath:e});if(!t.ok)throw Error(t.error??`unknown sqlite-vec load error`);return this.vector.extensionPath=t.extensionPath,this.vector.available=!0,!0}catch(e){let t=e instanceof Error?e.message:String(e);return this.vector.available=!1,this.vector.loadError=t,!1}}ensureVectorTable(e){this.vector.dims!==e&&(this.vector.dims&&this.vector.dims!==e&&this.dropVectorTable(),this.db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${G} USING vec0(\n id TEXT PRIMARY KEY,\n embedding FLOAT[${e}]\n)`),this.vector.dims=e)}dropVectorTable(){try{this.db.exec(`DROP TABLE IF EXISTS ${G}`)}catch{}}async withTimeout(e,t,n){if(!Number.isFinite(t)||t<=0)return await e;let r=null,i=new Promise((e,i)=>{r=setTimeout(()=>i(Error(n)),t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}ensureWatcher(){if(!this.config.sync.watch||this.watchers.length>0)return;let e=[o.join(this.memoryRoot,`MEMORY.md`),o.join(this.memoryRoot,`memory.md`),o.join(this.memoryRoot,`memory`)],t=()=>{this.dirty=!0,this.scheduleWatchSync()};for(let n of e)try{let e=l.watch(n,{recursive:!1},t);e.on(`error`,()=>{try{e.close()}catch{}}),this.watchers.push(e)}catch{}}scheduleWatchSync(){this.config.sync.watch&&(this.watchTimer&&clearTimeout(this.watchTimer),this.watchTimer=setTimeout(()=>{this.watchTimer=null,this.sync({reason:`watch`}).catch(()=>{})},this.config.sync.watchDebounceMs))}ensureSessionListener(){if(!this.config.experimental.sessionMemory)return;let e=t(this.dataDir,{storeName:this.sessionStoreName});try{let t=l.watch(e,{recursive:!0},(t,n)=>{if(!n||!n.endsWith(`transcript.jsonl`))return;let r=o.join(e,n);this.scheduleSessionDirty(r)});this.watchers.push(t)}catch{}}scheduleSessionDirty(e){this.config.experimental.sessionMemory&&(this.sessionPendingFiles.add(e),!this.sessionWatchTimer&&(this.sessionWatchTimer=setTimeout(()=>{this.sessionWatchTimer=null,this.processSessionDeltaBatch().catch(()=>{})},5e3)))}async processSessionDeltaBatch(){if(this.sessionPendingFiles.size===0)return;let e=Array.from(this.sessionPendingFiles);this.sessionPendingFiles.clear();let t=!1;for(let n of e){let e=await this.updateSessionDelta(n);if(!e)continue;let r=e.deltaBytes,i=e.deltaMessages,a=r<=0?e.pendingBytes>0:e.pendingBytes>=r,o=i<=0?e.pendingMessages>0:e.pendingMessages>=i;!a&&!o||(this.sessionsDirtyFiles.add(n),this.sessionsDirty=!0,e.pendingBytes=r>0?Math.max(0,e.pendingBytes-r):0,e.pendingMessages=i>0?Math.max(0,e.pendingMessages-i):0,t=!0)}t&&this.sync({reason:`session-delta`}).catch(()=>{})}async updateSessionDelta(e){let t=this.config.sync.sessions;if(!t)return null;let n;try{n=await a.stat(e)}catch{return null}let r=n.size,i=this.sessionDeltas.get(e);i||(i={lastSize:0,pendingBytes:0,pendingMessages:0},this.sessionDeltas.set(e,i));let o=Math.max(0,r-i.lastSize);return o===0&&r===i.lastSize?{deltaBytes:t.deltaBytes,deltaMessages:t.deltaMessages,pendingBytes:i.pendingBytes,pendingMessages:i.pendingMessages}:(r<i.lastSize?(i.lastSize=r,i.pendingBytes+=r,t.deltaMessages>0&&(t.deltaBytes<=0||i.pendingBytes<t.deltaBytes)&&(i.pendingMessages+=await this.countNewlines(e,0,r))):(i.pendingBytes+=o,t.deltaMessages>0&&(t.deltaBytes<=0||i.pendingBytes<t.deltaBytes)&&(i.pendingMessages+=await this.countNewlines(e,i.lastSize,r)),i.lastSize=r),this.sessionDeltas.set(e,i),{deltaBytes:t.deltaBytes,deltaMessages:t.deltaMessages,pendingBytes:i.pendingBytes,pendingMessages:i.pendingMessages})}async countNewlines(e,t,n){if(n<=t)return 0;let r;try{r=await a.open(e,`r`)}catch{return 0}try{let e=t,i=0,a=Buffer.alloc(64*1024);for(;e<n;){let t=Math.min(a.length,n-e),{bytesRead:o}=await r.read(a,0,t,e);if(o<=0)break;for(let e=0;e<o;e+=1)a[e]===10&&(i+=1);e+=o}return i}finally{await r.close()}}computeProviderKey(){return _(JSON.stringify({provider:this.provider.id,model:this.provider.model}))}resolveMemoryFilePath(e){let t=e.trim();if(!t)throw Error(`path required`);let n=o.isAbsolute(t)?o.resolve(t):o.resolve(this.memoryRoot,t),r=o.relative(this.memoryRoot,n).replace(/\\/g,`/`);if(!(r.length>0&&!r.startsWith(`..`)&&!o.isAbsolute(r)&&m(r))||!n.endsWith(`.md`))throw Error(`path required`);return{absPath:n,relPath:r}}applyEmbeddingProvider(){let e=this.config.embedding?.providerId?.trim();if(e){let t=w({providerId:e,dataDir:this.dataDir,memoryDir:this.memoryRoot});if(!t)throw Error(`Embedding provider not found: ${e}`);this.provider=t.provider,this.embeddingProviderId=e,this.providerKey=this.computeProviderKey(),this.dirty=!0;return}this.embeddingProviderId&&(this.provider=S(),this.embeddingProviderId=void 0,this.providerKey=this.computeProviderKey(),this.dirty=!0)}readMeta(){let e=this.db.prepare(`SELECT value FROM meta WHERE key = ?`).get(J);if(!e?.value)return null;try{return JSON.parse(e.value)}catch{return null}}writeMeta(e){let t=JSON.stringify(e);this.db.prepare(`INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`).run(J,t)}loadEmbeddingCache(e){if(!this.config.cache.enabled||e.length===0)return new Map;let t=Array.from(new Set(e.filter(Boolean)));if(t.length===0)return new Map;let n=new Map,r=[this.provider.id,this.provider.model,this.providerKey];for(let e=0;e<t.length;e+=400){let i=t.slice(e,e+400),a=i.map(()=>`?`).join(`, `),o=this.db.prepare(`SELECT hash, embedding FROM ${q}\n WHERE provider = ? AND model = ? AND provider_key = ? AND hash IN (${a})`).all(...r,...i);for(let e of o)n.set(e.hash,b(e.embedding))}return n}upsertEmbeddingCache(e){if(!this.config.cache.enabled||e.length===0)return;let t=Date.now(),n=this.db.prepare(`INSERT INTO ${q} (provider, model, provider_key, hash, embedding, dims, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(provider, model, provider_key, hash) DO UPDATE SET\n embedding=excluded.embedding,\n dims=excluded.dims,\n updated_at=excluded.updated_at`);for(let r of e){let e=r.embedding??[];n.run(this.provider.id,this.provider.model,this.providerKey,r.hash,JSON.stringify(e),e.length,t)}}async embedChunks(e){if(e.length===0)return[];let t=this.loadEmbeddingCache(e.map(e=>e.hash)),n=Array.from({length:e.length},()=>[]),r=[];for(let i=0;i<e.length;i+=1){let a=e[i],o=a?.hash?t.get(a.hash):void 0;o&&o.length>0?n[i]=o:a&&r.push({index:i,chunk:a})}if(r.length===0)return n;let i=await this.provider.embedBatch(r.map(e=>e.chunk.text)),a=[];for(let e=0;e<r.length;e+=1){let t=r[e],o=i[e]??[];n[t.index]=o,a.push({hash:t.chunk.hash,embedding:o})}return this.upsertEmbeddingCache(a),n}async indexFile(e,t){let n=y(t.content??await a.readFile(e.absPath,`utf-8`),{tokens:this.config.chunkTokens,overlap:this.config.chunkOverlap}).filter(e=>e.text.trim().length>0);t.source===`sessions`&&ee(n,t.lineMap);let r=await this.embedChunks(n),i=r.find(e=>e.length>0),o=i?await this.ensureVectorReady(i.length):!1,s=Date.now();if(o)try{this.db.prepare(`DELETE FROM ${G} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(e.path,t.source)}catch{}if(this.ftsAvailable)try{this.db.prepare(`DELETE FROM ${K} WHERE path = ? AND source = ? AND model = ?`).run(e.path,t.source,this.provider.model)}catch{}this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(e.path,t.source);for(let i=0;i<n.length;i+=1){let a=n[i],c=r[i]??[],l=_(`${t.source}:${e.path}:${a.startLine}:${a.endLine}:${a.hash}:${this.provider.model}`);if(this.db.prepare(`INSERT INTO chunks (id, path, source, start_line, end_line, hash, model, text, embedding, updated_at)
|
|
53
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
54
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
55
|
-
hash=excluded.hash,
|
|
56
|
-
model=excluded.model,
|
|
57
|
-
text=excluded.text,
|
|
58
|
-
embedding=excluded.embedding,
|
|
59
|
-
updated_at=excluded.updated_at`).run(l,e.path,t.source,a.startLine,a.endLine,a.hash,this.provider.model,a.text,JSON.stringify(c),s),o&&c.length>0){try{this.db.prepare(`DELETE FROM ${G} WHERE id = ?`).run(l)}catch{}this.db.prepare(`INSERT INTO ${G} (id, embedding) VALUES (?, ?)`).run(l,Buffer.from(new Float32Array(c).buffer))}this.ftsAvailable&&this.db.prepare(`INSERT INTO ${K} (text, id, path, source, model, start_line, end_line)\n VALUES (?, ?, ?, ?, ?, ?, ?)`).run(a.text,l,e.path,t.source,this.provider.model,a.startLine,a.endLine)}this.db.prepare(`INSERT INTO files (path, source, hash, mtime, size) VALUES (?, ?, ?, ?, ?)
|
|
60
|
-
ON CONFLICT(path) DO UPDATE SET
|
|
61
|
-
source=excluded.source,
|
|
62
|
-
hash=excluded.hash,
|
|
63
|
-
mtime=excluded.mtime,
|
|
64
|
-
size=excluded.size`).run(e.path,t.source,e.hash,e.mtimeMs,e.size)}buildSourceFilter(){let e=this.config.sources;return e.length?{sql:` AND source IN (${e.map(()=>`?`).join(`, `)})`,params:e}:{sql:``,params:[]}}async searchVector(e,t){return await U({db:this.db,vectorTable:G,providerModel:this.provider.model,queryVec:e,limit:t,snippetMaxChars:700,ensureVectorReady:async e=>await this.ensureVectorReady(e),sourceFilterVec:this.buildSourceFilter(),sourceFilterChunks:this.buildSourceFilter()})}async searchKeyword(e,t){return this.ftsAvailable?await pe({db:this.db,ftsTable:K,providerModel:this.provider.model,query:e,limit:t,snippetMaxChars:700,sourceFilter:this.buildSourceFilter(),buildFtsQuery:e=>I(e),bm25RankToScore:L}):[]}resetIndex(){if(this.db.exec(`DELETE FROM files`),this.db.exec(`DELETE FROM chunks`),this.ftsAvailable)try{this.db.exec(`DELETE FROM ${K}`)}catch{}this.dropVectorTable(),this.vector.dims=void 0,this.sessionsDirtyFiles.clear()}async syncAndPostCheck(e){try{await this.sync({reason:`mutation-postcheck`})}catch{this.searchFallbackOnly=!0;return}this.searchFallbackOnly=!this.indexHasSearchableData()}indexHasSearchableData(){try{if((this.db.prepare(`SELECT COUNT(*) as c FROM chunks`).get()?.c??0)>0)return!0}catch{}try{if(l.readdirSync(this.memoryRoot).filter(e=>e.endsWith(`.md`)).length>0)return!1;let e=o.join(this.memoryRoot,`memory`);return l.existsSync(e)?l.readdirSync(e).filter(e=>e.endsWith(`.md`)).length===0:!0}catch{return!1}}async fileScanSearch(e){let t=e.trim().toLowerCase();if(!t)return[];let n=await g(this.memoryRoot),r=[];for(let e of n){let n=``;try{n=await a.readFile(e,`utf-8`)}catch{continue}let i=o.relative(this.memoryRoot,e).replace(/\\/g,`/`);i.startsWith(`memory/`);let c=n.split(`
|
|
65
|
-
`);for(let n=0;n<c.length;n+=1){let a=c[n]??``,o=a.toLowerCase();if(!o.includes(t))continue;let l=o===t?1:Math.max(.2,t.length/Math.max(a.length,t.length));r.push({path:i||s(e),startLine:n+1,endLine:n+1,score:Number(l.toFixed(4)),snippet:a.slice(0,700),source:`memory`})}}return r.sort((e,t)=>t.score-e.score||e.path.localeCompare(t.path)||e.startLine-t.startLine),r.slice(0,this.config.maxResults)}getFtsRowCount(){if(this.ftsAvailable)try{return this.db.prepare(`SELECT COUNT(*) as c FROM ${K}`).get()?.c??0}catch{return}}buildRebuildSummary(e){let t=this.db.prepare(`SELECT COUNT(*) as c FROM chunks`).get();return{reason:e.reason,memoryFilesIndexed:e.memoryFilesIndexed,sessionFilesIndexed:e.sessionFilesIndexed,staleMemoryFilesRemoved:e.staleMemoryFilesRemoved,staleSessionFilesRemoved:e.staleSessionFilesRemoved,chunks:t?.c??0,ftsRows:this.getFtsRowCount(),fallbackActive:this.searchFallbackOnly,needsFullReindex:e.needsFullReindex}}async rebuild(e=`manual-rebuild`){return this.resetIndex(),this.dirty=!0,this.sessionsDirty=!0,await this.sync({reason:e,forceFullReindex:!0}),this.lastRebuildSummary??this.buildRebuildSummary({reason:e,memoryFilesIndexed:0,sessionFilesIndexed:0,staleMemoryFilesRemoved:0,staleSessionFilesRemoved:0,needsFullReindex:!0})}async sync(e){let t=this.readMeta(),n=e?.forceFullReindex||!t||t.model!==this.provider.model||t.provider!==this.provider.id||t.providerKey!==this.providerKey||t.chunkTokens!==this.config.chunkTokens||t.chunkOverlap!==this.config.chunkOverlap||this.vector.available&&!t?.vectorDims;n&&this.resetIndex();let r=await g(this.memoryRoot),i=(await Promise.all(r.map(async e=>v(e,this.memoryRoot)))).filter(e=>e!==null),a=new Set(i.map(e=>e.path)),o=0,s=i.map(e=>async()=>{let t=this.db.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`).get(e.path,`memory`);!n&&t?.hash===e.hash||(await this.indexFile(e,{source:`memory`}),o+=1)});for(let e of s)await e();let c=0,l=this.db.prepare(`SELECT path FROM files WHERE source = ?`).all(`memory`);for(let e of l)if(!a.has(e.path)){this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(e.path,`memory`),c+=1;try{this.db.prepare(`DELETE FROM ${G} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(e.path,`memory`)}catch{}if(this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(e.path,`memory`),this.ftsAvailable)try{this.db.prepare(`DELETE FROM ${K} WHERE path = ? AND source = ? AND model = ?`).run(e.path,`memory`,this.provider.model)}catch{}}let u={indexed:0,staleRemoved:0};this.config.experimental.sessionMemory&&(n||this.sessionsDirty)&&(u=await this.syncSessionFiles(n)),this.writeMeta({model:this.provider.model,provider:this.provider.id,providerKey:this.providerKey,chunkTokens:this.config.chunkTokens,chunkOverlap:this.config.chunkOverlap,...this.vector.available&&this.vector.dims?{vectorDims:this.vector.dims}:{}}),this.dirty=!1,this.searchFallbackOnly=!this.indexHasSearchableData(),this.lastRebuildSummary=this.buildRebuildSummary({reason:e?.reason??`sync`,memoryFilesIndexed:o,sessionFilesIndexed:u.indexed,staleMemoryFilesRemoved:c,staleSessionFilesRemoved:u.staleRemoved,needsFullReindex:!!n})}async syncSessionFiles(e){let t=await ve(this.dataDir,this.sessionStoreName),n=(await Promise.all(t.map(async e=>be(this.dataDir,e,this.sessionStoreName)))).filter(e=>e!==null),r=new Set(n.map(e=>e.path)),i=e||this.sessionsDirtyFiles.size===0,a=0;for(let t of n){if(!i&&!this.sessionsDirtyFiles.has(t.absPath))continue;let n=this.db.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`).get(t.path,`sessions`);if(!e&&n?.hash===t.hash){this.resetSessionDelta(t.absPath,t.size);continue}await this.indexFile(t,{source:`sessions`,content:t.content,lineMap:t.lineMap}),a+=1,this.resetSessionDelta(t.absPath,t.size)}let o=0,s=this.db.prepare(`SELECT path FROM files WHERE source = ?`).all(`sessions`);for(let e of s)if(!r.has(e.path)){this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(e.path,`sessions`),o+=1;try{this.db.prepare(`DELETE FROM ${G} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(e.path,`sessions`)}catch{}if(this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(e.path,`sessions`),this.ftsAvailable)try{this.db.prepare(`DELETE FROM ${K} WHERE path = ? AND source = ? AND model = ?`).run(e.path,`sessions`,this.provider.model)}catch{}}return this.sessionsDirty=!1,this.sessionsDirtyFiles.clear(),{indexed:a,staleRemoved:o}}resetSessionDelta(e,t){let n=this.sessionDeltas.get(e);n&&(n.lastSize=t,n.pendingBytes=0,n.pendingMessages=0)}decorateCitations(e){return this.config.citations===`off`?e:e.map(e=>{let t=`Source: ${e.path}#L${e.startLine}-L${e.endLine}`;return this.config.citations===`on`?{...e,citation:t,snippet:`${e.snippet}\n\n${t}`}:{...e,citation:t}})}decorateEntryIds(e){return e.map(e=>{if(e.id)return e;let t=xe(e.path,e.snippet,e.startLine);return{...e,id:t}})}},Se=e({createBuiltinMemoryProvider:()=>$});function $(e,t){let n=Q.get(e.dataDir,t?.includeSessions?{experimental:{sessionMemory:!0},sources:[`memory`,`sessions`],store:{sessionStoreName:e.sessionStoreName,vector:{enabled:!0}}}:e.sessionStoreName?{store:{sessionStoreName:e.sessionStoreName,vector:{enabled:!0}}}:void 0),r=e.memoryDir;return{id:`builtin-memory`,name:`Builtin Memory Provider`,status:()=>n.status(),search:async(e,t)=>n.search(e),getLines:async(e,t,r)=>{let i=Math.max(1,r-t+1),a=await n.readFile({relPath:e,from:t,lines:i});return a.text?a.text.split(`
|
|
66
|
-
`):[]},listFiles:async()=>g(r),append:async e=>n.appendToMemory(e),updateFile:async(e,t)=>{await n.replaceFile({relPath:e,content:t})},deleteFile:async e=>{await n.deleteFile(e)},sync:async e=>{if(e===`cli-rebuild`){await n.rebuild(e);return}await n.sync({reason:e??`provider-sync`})},noteSessionUpdate:e=>{let t=o.isAbsolute(e)?e:o.resolve(e);n.noteSessionUpdate(t)}}}export{ae as a,ie as i,$ as n,w as o,Q as r,g as s,Se as t};
|