@gencode/agents 0.6.1 → 0.7.0

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 CHANGED
@@ -1,5 +1,42 @@
1
1
  # @gencode/agents
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ace4220: Add thread goal audit events, live goal status updates, and objective-change steering across the goal control flow.
8
+ - 7cd5fcc: Add persisted thread goals with CLI controls, automatic continuation, and goal status reporting across sessions.
9
+
10
+ ### Patch Changes
11
+
12
+ - e1882f4: Retry 200-stream LLM payload errors when upstream 5xx details survive only in the error message text.
13
+ - 1df854a: Start work immediately after `/goal` activates or resumes a thread goal, while keeping non-executing goal commands short-circuited.
14
+ - 5422fc5: Add Bun runtime support to the requireNodeSqlite() function.
15
+ - cb8d8d7: - Dependency Migration : Added better-sqlite3@^12.10.0 and @types/better-sqlite3@^7.6.13 to dependencies, replacing the built-in node:sqlite module.
16
+ - Database Interface Updates : Changed all database type references from DatabaseSync (node:sqlite) to Database (better-sqlite3) across:
17
+ - manager.ts
18
+ - memory-schema.ts
19
+ - sqlite-vec.ts
20
+ - memory.test.ts
21
+ - SQLite Helper Refactor : Simplified sqlite.ts by removing Bun-specific SQLite handling ( bun:sqlite ) and creating a unified requireBetterSqlite() function.
22
+ - Extension Loading : Removed explicit enableLoadExtension(true) call in sqlite-vec.ts as better-sqlite3 handles extension loading differently.
23
+ - Updated dependencies [ace4220]
24
+ - Updated dependencies [7cd5fcc]
25
+ - @gencode/shared@0.2.0
26
+
27
+ ## Unreleased
28
+
29
+ ### Patch Changes
30
+
31
+ - Emit a WEB-channel-only `model_request` progress event before model invocation, including `systemPrompt`, tool definitions, and the full model request payload for console debugging.
32
+ - Export `buildOpenAICompletionsRequestParams()` from the OpenAI compat layer to reuse the real request-building path for debug previews.
33
+
34
+ ## 0.6.2
35
+
36
+ ### Patch Changes
37
+
38
+ - b739cce: Fix the published CLI bundle so `aimax -V` no longer fails with a duplicate ESM declaration error.
39
+
3
40
  ## 0.6.1
4
41
 
5
42
  ### 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-CpVlUp8c.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(`better-sqlite3`)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`SQLite support is unavailable (missing better-sqlite3). ${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(){return f(o.dirname(this.storePath)),new(he())(this.storePath)}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};
@@ -1,2 +1,2 @@
1
- import { S as AgentsConfig, _ as saveAgentsConfig, a as listAgents, b as AgentConfig, c as normalizeAgentId, d as resolveAgentDir, f as resolveAgentIdByBinding, g as resolveModelString, h as resolveModelFallbacks, i as getAgentConfig, l as removeAgent, m as resolveDefaultAgentId, n as addBinding, o as listBindings, p as resolveAgentsConfigPath, r as aimaxDir, s as loadAgentsConfig, t as addAgent, u as removeBindings, v as updateAgentIdentity, x as AgentModelConfig, y as AgentBinding } from "../index-pXTy2jgd.js";
1
+ import { S as AgentsConfig, _ as saveAgentsConfig, a as listAgents, b as AgentConfig, c as normalizeAgentId, d as resolveAgentDir, f as resolveAgentIdByBinding, g as resolveModelString, h as resolveModelFallbacks, i as getAgentConfig, l as removeAgent, m as resolveDefaultAgentId, n as addBinding, o as listBindings, p as resolveAgentsConfigPath, r as aimaxDir, s as loadAgentsConfig, t as addAgent, u as removeBindings, v as updateAgentIdentity, x as AgentModelConfig, y as AgentBinding } from "../index-Ci56oZD5.js";
2
2
  export { AgentBinding, AgentConfig, AgentModelConfig, AgentsConfig, addAgent, addBinding, aimaxDir, getAgentConfig, listAgents, listBindings, loadAgentsConfig, normalizeAgentId, removeAgent, removeBindings, resolveAgentDir, resolveAgentIdByBinding, resolveAgentsConfigPath, resolveDefaultAgentId, resolveModelFallbacks, resolveModelString, saveAgentsConfig, updateAgentIdentity };
@@ -1 +1 @@
1
- import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,u as g,v as _}from"../config-DG3Q1aJ6.js";export{h as addAgent,u as addBinding,p as aimaxDir,s as getAgentConfig,t as listAgents,d as listBindings,m as loadAgentsConfig,n as normalizeAgentId,c as removeAgent,g as removeBindings,r as resolveAgentDir,i as resolveAgentIdByBinding,f as resolveAgentsConfigPath,l as resolveDefaultAgentId,o as resolveModelFallbacks,a as resolveModelString,e as saveAgentsConfig,_ as updateAgentIdentity};
1
+ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,u as g,v as _}from"../config-CJ7qy-pr.js";export{h as addAgent,u as addBinding,p as aimaxDir,s as getAgentConfig,t as listAgents,d as listBindings,m as loadAgentsConfig,n as normalizeAgentId,c as removeAgent,g as removeBindings,r as resolveAgentDir,i as resolveAgentIdByBinding,f as resolveAgentsConfigPath,l as resolveDefaultAgentId,o as resolveModelFallbacks,a as resolveModelString,e as saveAgentsConfig,_ as updateAgentIdentity};
@@ -0,0 +1 @@
1
+ import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{T as t}from"./session-CpVlUp8c.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};
@@ -0,0 +1 @@
1
+ import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{T as t,j as n}from"./session-CpVlUp8c.js";import{t as r}from"./goal-events-BlRbQKm7.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.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { S as AgentsConfig, _ as saveAgentsConfig, a as listAgents, b as AgentConfig, c as normalizeAgentId, d as resolveAgentDir, f as resolveAgentIdByBinding, g as resolveModelString, h as resolveModelFallbacks, i as getAgentConfig, l as removeAgent, m as resolveDefaultAgentId, n as addBinding, o as listBindings, p as resolveAgentsConfigPath, s as loadAgentsConfig, t as addAgent, u as removeBindings, v as updateAgentIdentity, x as AgentModelConfig, y as AgentBinding } from "./index-pXTy2jgd.js";
1
+ import { S as AgentsConfig, _ as saveAgentsConfig, a as listAgents, b as AgentConfig, c as normalizeAgentId, d as resolveAgentDir, f as resolveAgentIdByBinding, g as resolveModelString, h as resolveModelFallbacks, i as getAgentConfig, l as removeAgent, m as resolveDefaultAgentId, n as addBinding, o as listBindings, p as resolveAgentsConfigPath, s as loadAgentsConfig, t as addAgent, u as removeBindings, v as updateAgentIdentity, x as AgentModelConfig, y as AgentBinding } from "./index-Ci56oZD5.js";
2
2
  import * as _gencode_shared0 from "@gencode/shared";
3
- import { AgentCustomProgressEvent, AgentProgressEvent, AgentProgressEvent as AgentProgressEvent$1, AgentProgressEvent as AgentProgressEvent$2, CallbackEventPayload, CallbackEventPayload as CallbackEventPayload$1, Channel, Channel as Channel$1, CollapseSpan, HitlCheckpoint, HitlCheckpoint as HitlCheckpoint$1, HitlHistoryEntry, HitlRequest, HitlRequest as HitlRequest$1, HitlResolution, HitlResolution as HitlResolution$1, HitlStatus, HitlToolContext, HitlToolContext as HitlToolContext$1, ModelUsageCheckpoint, PausedRunState, PausedRunState as PausedRunState$1, ReadStateRecord, RunResultPayload, RunResultPayload as RunResultPayload$1, SessionContextSnapshot, SessionMemorySnapshot, SessionMetadata, SessionMetadata as SessionMetadata$1, SessionSummary, SessionSummary as SessionSummary$1, SnipRecord, ToolResultReference, UiToolExtra, UiToolOutputSchema, UiToolPausedState, UiToolRequest, UiToolResult, UiToolValidationResult } from "@gencode/shared";
4
- import { AgentMessage, AgentTool } from "@mariozechner/pi-agent-core";
3
+ import { AgentCustomProgressEvent, AgentDiagnosticEvent, AgentProgressEvent, AgentProgressEvent as AgentProgressEvent$1, AgentProgressEvent as AgentProgressEvent$2, AgentProgressEventBase, CallbackEventPayload, CallbackEventPayload as CallbackEventPayload$1, Channel, Channel as Channel$1, CollapseSpan, GoalStatus, HitlCheckpoint, HitlCheckpoint as HitlCheckpoint$1, HitlHistoryEntry, HitlRequest, HitlRequest as HitlRequest$1, HitlResolution, HitlResolution as HitlResolution$1, HitlStatus, HitlToolContext, HitlToolContext as HitlToolContext$1, ModelUsageCheckpoint, PausedRunState, PausedRunState as PausedRunState$1, ReadStateRecord, RunResultPayload, RunResultPayload as RunResultPayload$1, SessionContextSnapshot, SessionMemorySnapshot, SessionMetadata, SessionMetadata as SessionMetadata$1, SessionSummary, SessionSummary as SessionSummary$1, SnipRecord, ThreadGoal, ToolResultReference, UiToolExtra, UiToolOutputSchema, UiToolPausedState, UiToolRequest, UiToolResult, UiToolValidationResult } from "@gencode/shared";
4
+ import { Agent, AgentMessage, AgentTool } from "@mariozechner/pi-agent-core";
5
5
  import { AssistantMessage, Message } from "@mariozechner/pi-ai";
6
6
 
7
7
  //#region src/loop-detection/tool-loop-detection.d.ts
@@ -336,7 +336,15 @@ type AgentRunParamsBase = {
336
336
  * Older turns are dropped before the history is sent to the LLM.
337
337
  * 0 or undefined means no limit.
338
338
  */
339
- historyLimit?: number; /** Internal multi-agent prompt/model/tool policy resolved at run time. */
339
+ historyLimit?: number;
340
+ /**
341
+ * Goal to create when this run establishes a new session (CLI `run --goal` without --session-id).
342
+ * Applied in runner after sessionId is assigned; not passed to the model as a tool.
343
+ */
344
+ pendingGoal?: {
345
+ objective: string;
346
+ tokenBudget: number | null;
347
+ }; /** Internal multi-agent prompt/model/tool policy resolved at run time. */
340
348
  agentPolicy?: AgentRuntimePolicyInput;
341
349
  };
342
350
  /** Parameters for running an agent session */
@@ -1803,6 +1811,18 @@ declare function createMemoryUpdateTool(dataDir: string, options?: MemoryToolOpt
1803
1811
  id: string;
1804
1812
  }>;
1805
1813
  //#endregion
1814
+ //#region src/runner/event-dispatcher.d.ts
1815
+ type EventDispatchParams = Pick<AgentRunParams, "onProgress" | "messageId" | "channel" | "subagentContext">;
1816
+ /**
1817
+ * Emits runner events to in-process listeners.
1818
+ */
1819
+ declare class RunEventDispatcher {
1820
+ private readonly params;
1821
+ constructor(params: EventDispatchParams);
1822
+ dispatchProgress(sessionId: string, event: AgentProgressEvent$2): Promise<void>;
1823
+ dispatchDiagnostic(sessionId: string, event: Omit<AgentDiagnosticEvent, keyof AgentProgressEventBase | "type">): Promise<void>;
1824
+ }
1825
+ //#endregion
1806
1826
  //#region src/tools/process-registry.d.ts
1807
1827
  type ProcessStatus = "running" | "completed" | "failed" | "killed" | "timeout";
1808
1828
  type ProcessSessionSnapshot = {
@@ -2264,7 +2284,8 @@ type SubagentToolsContext = {
2264
2284
  type: "skill_used";
2265
2285
  }>) => Promise<void>;
2266
2286
  contextManager?: ContextManager;
2267
- hitlResume?: AgentRunParams["hitlResume"]; /** Callback that runs a child agent; injected to avoid circular imports */
2287
+ hitlResume?: AgentRunParams["hitlResume"];
2288
+ eventDispatcher?: RunEventDispatcher; /** Callback that runs a child agent; injected to avoid circular imports */
2268
2289
  spawnFn: (params: AgentRunParams) => Promise<AgentRunResult>;
2269
2290
  };
2270
2291
  /**
@@ -2536,6 +2557,312 @@ declare function initializePluginSystem(options?: PluginSystemOptions): PluginSy
2536
2557
  //#region src/plugins/tool-hooks.d.ts
2537
2558
  declare function wrapToolsWithHooks(tools: AgentTool[], hooks: PluginHookRegistry, ctx: PluginHookAgentContext, runtime: PluginExecutionRuntime): AgentTool[];
2538
2559
  //#endregion
2560
+ //#region src/session/goal-events.d.ts
2561
+ type GoalEventSource = "cli" | "slash" | "tool" | "runner" | "store";
2562
+ type GoalEventAction = "created" | "replaced" | "updated" | "deleted" | "paused" | "resumed" | "cleared" | "completed" | "budget_limited" | "continuation_paused";
2563
+ type GoalEventRecord = {
2564
+ timestamp: string;
2565
+ sessionId: string;
2566
+ goalId: string | null;
2567
+ action: GoalEventAction;
2568
+ status: GoalStatus | null;
2569
+ source: GoalEventSource;
2570
+ detail?: Record<string, unknown>;
2571
+ };
2572
+ declare function goalEventsPath(dataDir: string, sessionId: string, options?: SessionPathOptions): string;
2573
+ declare function appendGoalEvent(dataDir: string, sessionId: string, record: Omit<GoalEventRecord, "timestamp" | "sessionId">, options?: SessionPathOptions): Promise<void>;
2574
+ //#endregion
2575
+ //#region src/session/goal-store.d.ts
2576
+ type GoalStoreOptions = SessionPathOptions & {
2577
+ eventSource?: GoalEventSource;
2578
+ };
2579
+ /** Returns the path to `goal.json` for a session. */
2580
+ declare function goalPath(dataDir: string, sessionId: string, options?: SessionPathOptions): string;
2581
+ /** Returns the path to `goal-objective.md` for a session. */
2582
+ declare function goalObjectiveMdPath(dataDir: string, sessionId: string, options?: SessionPathOptions): string;
2583
+ /**
2584
+ * Reads the current `goal.json`; returns `null` if none exists.
2585
+ */
2586
+ declare function readGoal(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise<ThreadGoal | null>;
2587
+ /**
2588
+ * Resolves the full objective text for a goal.
2589
+ * If the goal uses `objectiveRef`, reads the referenced markdown file.
2590
+ */
2591
+ declare function resolveGoalObjective(dataDir: string, sessionId: string, goal: ThreadGoal, options?: SessionPathOptions): Promise<string>;
2592
+ /**
2593
+ * Writes `goal.json` atomically (tmp + rename).
2594
+ *
2595
+ * If `objective` exceeds MAX_GOAL_OBJECTIVE_CHARS, spills to `goal-objective.md`
2596
+ * and sets `objectiveRef` to `"goal-objective.md"`.
2597
+ */
2598
+ declare function writeGoal(dataDir: string, sessionId: string, goal: Omit<ThreadGoal, "goalId" | "createdAt" | "updatedAt"> & {
2599
+ goalId?: string;
2600
+ createdAt?: string;
2601
+ updatedAt?: string;
2602
+ }, options?: GoalStoreOptions): Promise<ThreadGoal>;
2603
+ type GoalPatch = Partial<Pick<ThreadGoal, "status" | "tokenBudget" | "tokensUsed" | "timeUsedSeconds" | "pendingObjectiveUpdatedNotice">>;
2604
+ /**
2605
+ * Applies a partial update to an existing goal.json.
2606
+ * Returns the updated goal, or null if no goal exists.
2607
+ *
2608
+ * Objective changes must go through `writeGoal()` (handles spill files).
2609
+ */
2610
+ declare function updateGoal(dataDir: string, sessionId: string, updates: GoalPatch, options?: GoalStoreOptions): Promise<ThreadGoal | null>;
2611
+ /**
2612
+ * Removes `goal.json` (and `goal-objective.md` if present).
2613
+ * Also clears the goalStatus mirror.
2614
+ */
2615
+ declare function deleteGoal(dataDir: string, sessionId: string, options?: GoalStoreOptions): Promise<boolean>;
2616
+ /**
2617
+ * Syncs the `goalStatus` field in `session.json` to match the current goal.
2618
+ *
2619
+ * This is a **mirror** — the source of truth remains `goal.json`.
2620
+ * Call this whenever the goal status changes (set/update/delete/complete).
2621
+ *
2622
+ * Uses `updateSessionMetadata` which is a no-op if `session.json` doesn't exist yet.
2623
+ */
2624
+ declare function mirrorGoalStatusToSession(dataDir: string, sessionId: string, status: GoalStatus | null, options?: SessionPathOptions): Promise<void>;
2625
+ //#endregion
2626
+ //#region src/goal/accounting.d.ts
2627
+ type TokenUsage = {
2628
+ input: number;
2629
+ output: number;
2630
+ total: number;
2631
+ };
2632
+ /**
2633
+ * Per-turn accounting snapshot.
2634
+ * Tracks the active goal and the token baseline so we can compute deltas
2635
+ * at tool/turn boundaries.
2636
+ */
2637
+ interface TurnAccounting {
2638
+ turnId: string;
2639
+ activeGoalId: string | null;
2640
+ lastTokenUsage: TokenUsage;
2641
+ }
2642
+ /**
2643
+ * Wall-clock accounting snapshot.
2644
+ * Tracks the active goal and the last accounted time baseline.
2645
+ */
2646
+ interface WallClockAccounting {
2647
+ activeGoalId: string | null;
2648
+ /** Date.now() at last flush */
2649
+ lastAccountedAt: number;
2650
+ }
2651
+ /**
2652
+ * Runtime accounting state for a single runAgent call.
2653
+ * Created fresh each run, disposed on completion.
2654
+ */
2655
+ declare class GoalAccounting {
2656
+ turn: TurnAccounting | null;
2657
+ wallClock: WallClockAccounting;
2658
+ /** Resets wall-clock baseline (e.g. when a new goal becomes active mid-turn). */
2659
+ resetWallClock(): void;
2660
+ /**
2661
+ * Marks the active goal for both turn-level and wall-clock tracking.
2662
+ * Resets wall-clock baseline when the active goal changes.
2663
+ */
2664
+ markActiveGoal(turnId: string | null, goalId: string, tokenUsage: TokenUsage): void;
2665
+ /** Clears active goal (e.g. when paused, completed, or interrupt). */
2666
+ clearActiveGoal(): void;
2667
+ /**
2668
+ * Computes token delta since the last accounting checkpoint.
2669
+ * Uses: non-cached input + output (aligns with codex goal_token_delta_for_usage).
2670
+ */
2671
+ tokenDeltaSinceLastAccounting(currentUsage: TokenUsage): number;
2672
+ /**
2673
+ * Returns wall-clock seconds since the last accounting checkpoint.
2674
+ */
2675
+ timeDeltaSecondsSinceLastAccounting(): number;
2676
+ /**
2677
+ * Marks the current usage as accounted (updates the turn-level baseline).
2678
+ */
2679
+ markAccounted(currentUsage: TokenUsage, accountedSeconds: number): void;
2680
+ }
2681
+ /**
2682
+ * Result of flushing accounting deltas to the goal store.
2683
+ */
2684
+ type AccountingFlushResult = {
2685
+ goal: ThreadGoal | null;
2686
+ budgetLimited: boolean;
2687
+ };
2688
+ /**
2689
+ * Flushes accumulated token and time deltas to goal.json.
2690
+ *
2691
+ * Reads the current goal, applies deltas, and writes back.
2692
+ * If the goal has a tokenBudget and tokensUsed exceeds it,
2693
+ * sets status to "budget_limited".
2694
+ *
2695
+ * @returns the updated goal (or null if no active goal).
2696
+ */
2697
+ declare function flushAccounting(dataDir: string, sessionId: string, accounting: GoalAccounting, currentUsage: TokenUsage, options?: {
2698
+ storeName?: string;
2699
+ eventSource?: GoalEventSource;
2700
+ }): Promise<AccountingFlushResult>;
2701
+ //#endregion
2702
+ //#region src/goal/prompts.d.ts
2703
+ /**
2704
+ * Builds the continuation prompt for an idle goal continuation turn.
2705
+ *
2706
+ * Tells the model:
2707
+ * - The active objective and budget
2708
+ * - To continue working toward the objective
2709
+ * - To perform a completion audit before declaring complete
2710
+ * - Not to mark complete merely because budget is exhausted
2711
+ */
2712
+ declare function buildContinuationPrompt(goal: ThreadGoal, objectiveText: string): string;
2713
+ /**
2714
+ * Builds the budget-limit steering prompt.
2715
+ *
2716
+ * Tells the model the token budget has been exhausted.
2717
+ * The model should wrap up the current turn, summarize progress,
2718
+ * and NOT call update_goal(complete) unless truly done.
2719
+ */
2720
+ declare function buildBudgetLimitPrompt(goal: ThreadGoal, objectiveText: string): string;
2721
+ /**
2722
+ * Builds the objective-updated steering prompt.
2723
+ *
2724
+ * Injected once when the user replaces the goal objective externally (CLI).
2725
+ * Tells the model the objective has changed and supersedes any previous one.
2726
+ */
2727
+ declare function buildObjectiveUpdatedPrompt(goal: ThreadGoal, objectiveText: string): string;
2728
+ /**
2729
+ * Builds a hidden user-context message item for goal steering.
2730
+ *
2731
+ * The `<goal_context>` wrapper signals that this should NOT be persisted
2732
+ * to transcript.jsonl.
2733
+ */
2734
+ interface GoalContextItem {
2735
+ role: "user";
2736
+ content: string;
2737
+ }
2738
+ declare function buildGoalContextItem(prompt: string): GoalContextItem;
2739
+ /**
2740
+ * Checks if a message content string is a goal context fragment.
2741
+ */
2742
+ declare function isGoalContext(content: string): boolean;
2743
+ //#endregion
2744
+ //#region src/goal/continuation.d.ts
2745
+ /**
2746
+ * Environment variable to disable goal continuation entirely.
2747
+ * Set to "0" (or any falsy value) to disable.
2748
+ */
2749
+ declare const ENV_GOAL_CONTINUATION = "AIMAX_GOAL_CONTINUATION";
2750
+ /**
2751
+ * Per-run continuation state.
2752
+ * Tracks how many continuations have been performed in the current runAgent call.
2753
+ */
2754
+ declare class ContinuationState {
2755
+ continuationCount: number;
2756
+ lastTurnHadOutput: boolean;
2757
+ /** True after the one-shot budget-limit wrap-up turn has run. */
2758
+ budgetWrapUpDone: boolean;
2759
+ /** Resets the count (used when user sends a new turn). */
2760
+ reset(): void;
2761
+ }
2762
+ /**
2763
+ * Checks whether goal continuation is globally enabled via environment variable.
2764
+ */
2765
+ declare function isContinuationEnabled(): boolean;
2766
+ /**
2767
+ * Checks all continuation gates.
2768
+ *
2769
+ * Returns true if continuation should proceed.
2770
+ */
2771
+ declare function shouldContinueGoal(dataDir: string, sessionId: string, state: ContinuationState, options?: {
2772
+ storeName?: string;
2773
+ }): Promise<boolean>;
2774
+ type GoalContinuationTurnResult = {
2775
+ text: string;
2776
+ inputTokens: number;
2777
+ outputTokens: number;
2778
+ error?: string;
2779
+ toolResultCount?: number;
2780
+ };
2781
+ /** True when a continuation turn produced assistant text or tool results. */
2782
+ declare function continuationTurnHadMeaningfulOutput(turn: GoalContinuationTurnResult): boolean;
2783
+ type GoalContinuationInput = {
2784
+ agent: Agent;
2785
+ dataDir: string;
2786
+ sessionId: string;
2787
+ sessionStoreName?: string;
2788
+ state: ContinuationState;
2789
+ accounting: GoalAccounting;
2790
+ abortSignal?: AbortSignal; /** Callback to execute a turn with the given prompt string */
2791
+ executeTurn: (prompt: string) => Promise<GoalContinuationTurnResult>; /** Callback to flush accounting after continuation turn */
2792
+ flushAccountingAfterTurn?: (usage: TokenUsage) => Promise<void>;
2793
+ };
2794
+ /**
2795
+ * Attempts to start a goal continuation turn.
2796
+ *
2797
+ * Returns true if a continuation was started, false if gates prevent it.
2798
+ */
2799
+ declare function maybeContinueGoalIfIdle(input: GoalContinuationInput): Promise<boolean>;
2800
+ //#endregion
2801
+ //#region src/goal/cli-apply.d.ts
2802
+ declare class GoalConflictError extends Error {
2803
+ readonly existingObjectivePreview: string;
2804
+ constructor(message: string, existingObjectivePreview: string);
2805
+ }
2806
+ type ApplyCliGoalInput = {
2807
+ dataDir: string;
2808
+ sessionId: string;
2809
+ objective: string; /** undefined = leave budget unchanged; null = unlimited */
2810
+ tokenBudget?: number | null;
2811
+ force?: boolean;
2812
+ storeName?: string;
2813
+ };
2814
+ type ApplyCliGoalResult = {
2815
+ action: "created";
2816
+ goal: ThreadGoal;
2817
+ } | {
2818
+ action: "replaced";
2819
+ goal: ThreadGoal;
2820
+ } | {
2821
+ action: "unchanged";
2822
+ goal: ThreadGoal;
2823
+ } | {
2824
+ action: "updated";
2825
+ goal: ThreadGoal;
2826
+ };
2827
+ /**
2828
+ * Applies an external goal set from CLI `run --goal` / `resume --goal`.
2829
+ *
2830
+ * - No existing goal → create
2831
+ * - Same canonical objective → preserve goalId/progress (optional budget/status patch)
2832
+ * - Different objective → requires `force`, otherwise throws GoalConflictError
2833
+ */
2834
+ declare function applyCliGoalBeforeRun(input: ApplyCliGoalInput): Promise<ApplyCliGoalResult>;
2835
+ //#endregion
2836
+ //#region src/goal/steering.d.ts
2837
+ type ObjectiveUpdatedSteeringPrep = {
2838
+ prompt: string | Message[]; /** True when an objective-updated steering block was prepended (flag not yet cleared). */
2839
+ hadObjectiveUpdatedSteering: boolean;
2840
+ };
2841
+ /**
2842
+ * Prepends a one-shot objective-updated `<goal_context>` steering prompt when
2843
+ * `goal.json.pendingObjectiveUpdatedNotice` is set.
2844
+ *
2845
+ * Does **not** clear the flag — call `confirmObjectiveUpdatedSteeringConsumed`
2846
+ * after the first agent turn completes successfully.
2847
+ */
2848
+ declare function prependObjectiveUpdatedSteeringIfNeeded(dataDir: string, sessionId: string, prompt: string | Message[], options?: {
2849
+ storeName?: string;
2850
+ }): Promise<ObjectiveUpdatedSteeringPrep>;
2851
+ /**
2852
+ * Clears `pendingObjectiveUpdatedNotice` after steering was consumed by a
2853
+ * successful first agent turn.
2854
+ */
2855
+ declare function confirmObjectiveUpdatedSteeringConsumed(dataDir: string, sessionId: string, options?: {
2856
+ storeName?: string;
2857
+ }): Promise<void>;
2858
+ //#endregion
2859
+ //#region src/goal/notify.d.ts
2860
+ type GoalUpdatedAction = GoalEventAction | "cleared";
2861
+ declare function emitGoalUpdatedProgress(eventDispatcher: RunEventDispatcher, sessionId: string, params: {
2862
+ action: GoalUpdatedAction;
2863
+ goal?: ThreadGoal | null;
2864
+ }): Promise<void>;
2865
+ //#endregion
2539
2866
  //#region src/hitl/types.d.ts
2540
2867
  /** Information about the tool call that triggered the HITL pause. */
2541
2868
  /** Full internal context carried by a HitlPauseSignal. */
@@ -2725,4 +3052,4 @@ declare function formatClarifyResolution(resolution: HitlResolution): string;
2725
3052
  declare function formatReviewResolution(resolution: HitlResolution): string;
2726
3053
  declare function buildResumeNarration(resolution: HitlResolution, kind: string): string;
2727
3054
  //#endregion
2728
- export { AgentBinding, AgentConfig, type AgentConfigSource, type AgentCustomProgressEvent, type AgentDefinition, type AgentDefinitionsContext, type AgentDefinitionsStats, type AgentDirectoryCandidate, AgentModelConfig, type AgentProgressEvent, type AgentRunParams, type AgentRunResult, type AgentRuntimePolicy, type AgentRuntimePolicyInput, type AgentScanOptions, type AgentVisibility, AgentsConfig, type ArtifactOpInput, type ArtifactOperation, type ArtifactOperationInput, type ArtifactOperationName, type ArtifactOperationType, type AutoSkillCategory, type AutoSkillIndexEntry, type AutoSkillListItem, type AutoSkillListOptions, type AutoSkillSearchOptions, type AutoSkillSearchResult, type AutoSkillStatus, type AutoSkillViewOptions, type AutoSkillViewResult, AutoSkillsLoader, type AutoSkillsLoaderOptions, BOOTSTRAP_FILE_NAMES, BOOTSTRAP_MAX_CHARS, BOOTSTRAP_TOTAL_MAX_CHARS, type BootstrapContextFile, type BootstrapEnsureResult, type BootstrapFile, type BootstrapMountResult, type BootstrapMountStatus, type CallbackEventPayload, type CallbackPayload, type Channel, type ContextManager, type CronExecutionRecord, DEFAULT_SESSION_STORE_NAME, type EmbeddingProvider, type EmbeddingProviderContext, type EmbeddingProviderFactory, type EmbeddingProviderRegistration, HITL_MESSAGES, type HitlPauseContext, HitlPauseSignal, type HitlToolContext, MAX_ARTIFACT_CONTENT_CHARS, MAX_CHILDREN_PER_SESSION, MAX_SUBAGENT_DEPTH, type MemoryCallOptions, type MemoryChangeSource, type MemoryChangedEvent, type MemoryChangedHandler, MemoryIndexManager, type MemoryProvider, type MemoryProviderContext, type MemoryProviderFactory, type MemoryProviderRegistration, type MemoryProviderStatus, type MemoryRebuildSummary, type MemorySearchOptions, type MemorySearchResult, type NormalizedPluginsConfig, PLUGIN_MANIFEST_FILENAME, PLUGIN_MANIFEST_FILENAMES, type PersistedSubagentRunRecord, type PersistedToolResult, type PluginApi, type PluginCandidate, type PluginConfigUiHint, type PluginCustomProgressInput, type PluginDiagnostic, type PluginDiscoveryOptions, type PluginDiscoveryResult, type PluginEntryConfig, type PluginExecutionRuntime, type PluginHookAfterCompactionEvent, type PluginHookAfterPromptBuildEvent, type PluginHookAfterToolCallEvent, type PluginHookAgentContext, type PluginHookAgentEndEvent, type PluginHookAssistantMessageEndEvent, type PluginHookBeforeCompactionEvent, type PluginHookBeforeCompactionResult, type PluginHookBeforeModelResolveEvent, type PluginHookBeforeModelResolveResult, type PluginHookBeforePromptBuildEvent, type PluginHookBeforePromptBuildResult, type PluginHookBeforeToolCallEvent, type PluginHookBeforeToolCallResult, type PluginHookDreamGateEvent, type PluginHookDreamGateResult, type PluginHookHandlerMap, type PluginHookLlmInputEvent, type PluginHookLlmOutputEvent, type PluginHookMemoryChangedEvent, type PluginHookName, PluginHookRegistry, type PluginHookSessionEndEvent, type PluginHookSessionResetEvent, type PluginHookSessionStartEvent, type PluginKind, type PluginManifest, type PluginManifestLoadResult, type PluginManifestRegistry, type PluginOrigin, type PluginProgressEmitter, type PluginRecord, type PluginRegistry, type PluginRuntime, type PluginRuntimeContext, type PluginSystem, type PluginSystemOptions, type PluginToolOptions, PluginToolRegistry, type PluginUiToolDescriptor, type PluginUiToolOptions, type PluginsConfig, type PluginsConfigValidationResult, type RegisteredPluginTool, type ResumeOptions, type ResumeValidationResult, type RunResultPayload, SYSTEM_AGENTS_DIR, type SessionContextStore, type SessionExport, type SessionInspection, type SessionMetadata, type SessionMetadataUpdate, type SessionSummary, type Skill, type SkillDirectory, type SkillViewResult, type SlashCommandList, type SubagentContext, SubagentRegistry, type SubagentRunRecord, type SubagentStatus, type SubagentToolsContext, type SystemPromptParams, type ToolLoopDetectionConfig, type TranscriptEntry, type UiToolInputSchema, type UiToolOptions, UiToolPauseSignal, addAgent, addBinding, agentDirCandidates, agentVisibility, aimaxDir, appendArtifactOperation, appendCronExecutionRecord, appendRecentToMemory, appendSessionFile, appendToMemory, appendTranscriptEntry, approvalSummaryFromResolution, artifactsPath, atomicWriteSessionFile, autoSkillsDir, bootstrapMountLayout, buildAgentDelegationPrompt, buildAgentTaskPrompt, buildBootstrapContextFiles, buildResumeNarration, buildSkillsPrompt, buildSubagentAnnounceMessage, buildSystemPrompt, cleanupOldSubagentRecords, clearPendingHitl, clearPendingUiTool, collapseLogPath, contextSnapshotPath, createAgentDefinitionsContext, createAgentTools, createApplyPatchTool, createAutoSkillCategoriesTool, createAutoSkillListTool, createAutoSkillSearchTool, createAutoSkillViewTool, createAutoSkillsLoader, createBashTool, createBatchSubagentSpawnTool, createBuiltinMemoryProvider, createContextManager, createEditFileTool, createExecTool, createImageTool, createListDirTool, createMemoryAppendTool, createMemoryForgetTool, createMemoryGetTool, createMemoryListTool, createMemoryLogTool, createMemorySearchTool, createMemoryUpdateTool, createMemoryWriteTool, createPendingHitl, createPendingUiTool, createPluginProgressEmitter, createPluginRuntime, createProcessTool, createReadFileTool, createSession, createSessionContextStore, createSessionSearchTool, createSkillListTool, createSkillLoadTool, createSubagentSpawnTool, createSubagentsTool, createUiTool, createWriteFileTool, cronExecutionsPath, defaultUiToolInputSchema, deleteMemoryFile, discoverAIMaxPlugins, ensureBootstrapMountLayout, ensureSession, exportSession, filterSkillsForAgent, filterToolsForAgent, findAgentDefinition, findSkillByName, formatApprovalResolution, formatClarifyResolution, formatReviewResolution, generateSessionTitle, getAgentConfig, getMemoryLines, hasBootstrapSentinel, hitlHistoryPath, initializePluginSystem, inspectBootstrapMountLayout, inspectSession, isBootstrapMountLayoutReady, isHitlPauseSignal, isUiToolPauseSignal, listAgents, listAvailableSlashCommands, listBindings, listMemoryFiles, listSessionSummaries, listSessions, listSubagentRunsFromDisk, loadAgentDefinitionsFromDir, loadAgentsConfig, loadArtifactOperations, loadBootstrapFiles, loadCronExecutionRecords, readPendingHitl as loadPendingHitl, readPendingHitl, readPendingUiTool as loadPendingUiTool, readPendingUiTool, loadPluginManifest, loadPluginManifestRegistry, loadPlugins, loadSessionContextSnapshot, loadSessionMetadata, loadSkillView, loadSkills, loadSkillsFromDirs, loadSkillsWithPluginDirs, loadSubagentRegistryFromDisk, loadTranscript, memoryDir, metadataPath, normalizeAgentId, normalizePluginsConfig, normalizeSessionStoreName, parseAgentDefinition, pendingHitlPath, pendingUiToolPath, primaryMemoryPath, publicAgentDefinitions, readHitlHistory, readMemoryFile, readPrimaryMemory, readSessionFile, readSessionFileContent, registerEmbeddingProvider, registerMemoryProvider, removeAgent, removeBindings, replaceMemoryFile, resetEmbeddingProviderRegistryForTests, resetMemoryProviderRegistryForTests, resolveAgentDefinitionsContext, resolveAgentDir, resolveAgentIdByBinding, resolveAgentsConfigPath, resolveDefaultAgentId, resolveEmbeddingProvider, resolveHitlRequest, resolveHitlRequest as resolvePendingHitl, resolveMemoryProvider, resolveModelFallbacks, resolveModelString, resolvePendingUiTool, resolvePluginManifestPath, rewriteTranscript, runAgent, saveAgentsConfig, saveSessionMetadata, saveSubagentRegistryToDisk, scanAgentDefinitions, searchMemory, sessionDir, sessionMemoryPath, sessionsDir, skillsDir, toolResultsDir, transcriptPath, transitionHitlStatus, updateAgentIdentity, updateSessionMetadata, validatePluginsConfig, validateResume, wrapToolsWithHooks, writeSessionFile };
3055
+ export { type AccountingFlushResult, AgentBinding, AgentConfig, type AgentConfigSource, type AgentCustomProgressEvent, type AgentDefinition, type AgentDefinitionsContext, type AgentDefinitionsStats, type AgentDirectoryCandidate, AgentModelConfig, type AgentProgressEvent, type AgentRunParams, type AgentRunResult, type AgentRuntimePolicy, type AgentRuntimePolicyInput, type AgentScanOptions, type AgentVisibility, AgentsConfig, type ApplyCliGoalInput, type ApplyCliGoalResult, type ArtifactOpInput, type ArtifactOperation, type ArtifactOperationInput, type ArtifactOperationName, type ArtifactOperationType, type AutoSkillCategory, type AutoSkillIndexEntry, type AutoSkillListItem, type AutoSkillListOptions, type AutoSkillSearchOptions, type AutoSkillSearchResult, type AutoSkillStatus, type AutoSkillViewOptions, type AutoSkillViewResult, AutoSkillsLoader, type AutoSkillsLoaderOptions, BOOTSTRAP_FILE_NAMES, BOOTSTRAP_MAX_CHARS, BOOTSTRAP_TOTAL_MAX_CHARS, type BootstrapContextFile, type BootstrapEnsureResult, type BootstrapFile, type BootstrapMountResult, type BootstrapMountStatus, type CallbackEventPayload, type CallbackPayload, type Channel, type ContextManager, ContinuationState, type CronExecutionRecord, DEFAULT_SESSION_STORE_NAME, ENV_GOAL_CONTINUATION, type EmbeddingProvider, type EmbeddingProviderContext, type EmbeddingProviderFactory, type EmbeddingProviderRegistration, GoalAccounting, GoalConflictError, type GoalContinuationTurnResult, type GoalEventAction, type GoalEventRecord, type GoalEventSource, type GoalPatch, HITL_MESSAGES, type HitlPauseContext, HitlPauseSignal, type HitlToolContext, MAX_ARTIFACT_CONTENT_CHARS, MAX_CHILDREN_PER_SESSION, MAX_SUBAGENT_DEPTH, type MemoryCallOptions, type MemoryChangeSource, type MemoryChangedEvent, type MemoryChangedHandler, MemoryIndexManager, type MemoryProvider, type MemoryProviderContext, type MemoryProviderFactory, type MemoryProviderRegistration, type MemoryProviderStatus, type MemoryRebuildSummary, type MemorySearchOptions, type MemorySearchResult, type NormalizedPluginsConfig, type ObjectiveUpdatedSteeringPrep, PLUGIN_MANIFEST_FILENAME, PLUGIN_MANIFEST_FILENAMES, type PersistedSubagentRunRecord, type PersistedToolResult, type PluginApi, type PluginCandidate, type PluginConfigUiHint, type PluginCustomProgressInput, type PluginDiagnostic, type PluginDiscoveryOptions, type PluginDiscoveryResult, type PluginEntryConfig, type PluginExecutionRuntime, type PluginHookAfterCompactionEvent, type PluginHookAfterPromptBuildEvent, type PluginHookAfterToolCallEvent, type PluginHookAgentContext, type PluginHookAgentEndEvent, type PluginHookAssistantMessageEndEvent, type PluginHookBeforeCompactionEvent, type PluginHookBeforeCompactionResult, type PluginHookBeforeModelResolveEvent, type PluginHookBeforeModelResolveResult, type PluginHookBeforePromptBuildEvent, type PluginHookBeforePromptBuildResult, type PluginHookBeforeToolCallEvent, type PluginHookBeforeToolCallResult, type PluginHookDreamGateEvent, type PluginHookDreamGateResult, type PluginHookHandlerMap, type PluginHookLlmInputEvent, type PluginHookLlmOutputEvent, type PluginHookMemoryChangedEvent, type PluginHookName, PluginHookRegistry, type PluginHookSessionEndEvent, type PluginHookSessionResetEvent, type PluginHookSessionStartEvent, type PluginKind, type PluginManifest, type PluginManifestLoadResult, type PluginManifestRegistry, type PluginOrigin, type PluginProgressEmitter, type PluginRecord, type PluginRegistry, type PluginRuntime, type PluginRuntimeContext, type PluginSystem, type PluginSystemOptions, type PluginToolOptions, PluginToolRegistry, type PluginUiToolDescriptor, type PluginUiToolOptions, type PluginsConfig, type PluginsConfigValidationResult, type RegisteredPluginTool, type ResumeOptions, type ResumeValidationResult, type RunResultPayload, SYSTEM_AGENTS_DIR, type SessionContextStore, type SessionExport, type SessionInspection, type SessionMetadata, type SessionMetadataUpdate, type SessionSummary, type Skill, type SkillDirectory, type SkillViewResult, type SlashCommandList, type SubagentContext, SubagentRegistry, type SubagentRunRecord, type SubagentStatus, type SubagentToolsContext, type SystemPromptParams, type ToolLoopDetectionConfig, type TranscriptEntry, type TurnAccounting, type UiToolInputSchema, type UiToolOptions, UiToolPauseSignal, type WallClockAccounting, addAgent, addBinding, agentDirCandidates, agentVisibility, aimaxDir, appendArtifactOperation, appendCronExecutionRecord, appendGoalEvent, appendRecentToMemory, appendSessionFile, appendToMemory, appendTranscriptEntry, applyCliGoalBeforeRun, approvalSummaryFromResolution, artifactsPath, atomicWriteSessionFile, autoSkillsDir, bootstrapMountLayout, buildAgentDelegationPrompt, buildAgentTaskPrompt, buildBootstrapContextFiles, buildBudgetLimitPrompt, buildContinuationPrompt, buildGoalContextItem, buildObjectiveUpdatedPrompt, buildResumeNarration, buildSkillsPrompt, buildSubagentAnnounceMessage, buildSystemPrompt, cleanupOldSubagentRecords, clearPendingHitl, clearPendingUiTool, collapseLogPath, confirmObjectiveUpdatedSteeringConsumed, contextSnapshotPath, continuationTurnHadMeaningfulOutput, createAgentDefinitionsContext, createAgentTools, createApplyPatchTool, createAutoSkillCategoriesTool, createAutoSkillListTool, createAutoSkillSearchTool, createAutoSkillViewTool, createAutoSkillsLoader, createBashTool, createBatchSubagentSpawnTool, createBuiltinMemoryProvider, createContextManager, createEditFileTool, createExecTool, createImageTool, createListDirTool, createMemoryAppendTool, createMemoryForgetTool, createMemoryGetTool, createMemoryListTool, createMemoryLogTool, createMemorySearchTool, createMemoryUpdateTool, createMemoryWriteTool, createPendingHitl, createPendingUiTool, createPluginProgressEmitter, createPluginRuntime, createProcessTool, createReadFileTool, createSession, createSessionContextStore, createSessionSearchTool, createSkillListTool, createSkillLoadTool, createSubagentSpawnTool, createSubagentsTool, createUiTool, createWriteFileTool, cronExecutionsPath, defaultUiToolInputSchema, deleteGoal, deleteMemoryFile, discoverAIMaxPlugins, emitGoalUpdatedProgress, ensureBootstrapMountLayout, ensureSession, exportSession, filterSkillsForAgent, filterToolsForAgent, findAgentDefinition, findSkillByName, flushAccounting, formatApprovalResolution, formatClarifyResolution, formatReviewResolution, generateSessionTitle, getAgentConfig, getMemoryLines, goalEventsPath, goalObjectiveMdPath, goalPath, hasBootstrapSentinel, hitlHistoryPath, initializePluginSystem, inspectBootstrapMountLayout, inspectSession, isBootstrapMountLayoutReady, isContinuationEnabled, isGoalContext, isHitlPauseSignal, isUiToolPauseSignal, listAgents, listAvailableSlashCommands, listBindings, listMemoryFiles, listSessionSummaries, listSessions, listSubagentRunsFromDisk, loadAgentDefinitionsFromDir, loadAgentsConfig, loadArtifactOperations, loadBootstrapFiles, loadCronExecutionRecords, readPendingHitl as loadPendingHitl, readPendingHitl, readPendingUiTool as loadPendingUiTool, readPendingUiTool, loadPluginManifest, loadPluginManifestRegistry, loadPlugins, loadSessionContextSnapshot, loadSessionMetadata, loadSkillView, loadSkills, loadSkillsFromDirs, loadSkillsWithPluginDirs, loadSubagentRegistryFromDisk, loadTranscript, maybeContinueGoalIfIdle, memoryDir, metadataPath, mirrorGoalStatusToSession, normalizeAgentId, normalizePluginsConfig, normalizeSessionStoreName, parseAgentDefinition, pendingHitlPath, pendingUiToolPath, prependObjectiveUpdatedSteeringIfNeeded, primaryMemoryPath, publicAgentDefinitions, readGoal, readHitlHistory, readMemoryFile, readPrimaryMemory, readSessionFile, readSessionFileContent, registerEmbeddingProvider, registerMemoryProvider, removeAgent, removeBindings, replaceMemoryFile, resetEmbeddingProviderRegistryForTests, resetMemoryProviderRegistryForTests, resolveAgentDefinitionsContext, resolveAgentDir, resolveAgentIdByBinding, resolveAgentsConfigPath, resolveDefaultAgentId, resolveEmbeddingProvider, resolveGoalObjective, resolveHitlRequest, resolveHitlRequest as resolvePendingHitl, resolveMemoryProvider, resolveModelFallbacks, resolveModelString, resolvePendingUiTool, resolvePluginManifestPath, rewriteTranscript, runAgent, saveAgentsConfig, saveSessionMetadata, saveSubagentRegistryToDisk, scanAgentDefinitions, searchMemory, sessionDir, sessionMemoryPath, sessionsDir, shouldContinueGoal, skillsDir, toolResultsDir, transcriptPath, transitionHitlStatus, updateAgentIdentity, updateGoal, updateSessionMetadata, validatePluginsConfig, validateResume, wrapToolsWithHooks, writeGoal, writeSessionFile };