@gencode/agents 0.16.1 → 0.16.2

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,12 @@
1
1
  # @gencode/agents
2
2
 
3
+ ## 0.16.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 56d8304: Plugin hook handlers now receive the current external `messageId` on `ctx.messageId` when a run is started with `--message-id` or an equivalent API option. Existing callback, websocket, and progress payloads keep their previous `messageId` behavior.
8
+ - a4171d5: Avoid recursive filesystem watching of `.aimax/sessions`, `.aimax/tasks`, and other session stores during memory indexing. Session transcript updates are now tracked through the existing explicit transcript update notification path, reducing watcher usage in large deployments while preserving memory search behavior for normal `aimax run` and `resume` flows.
9
+
3
10
  ## 0.16.1
4
11
 
5
12
  ### Patch Changes
@@ -1,4 +1,4 @@
1
- import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{A as t,C as n,L as r}from"./session-CvZsdTZJ.js";import{o as i,r as a}from"./provider-registry-DPbmbWqS.js";import{createRequire as o}from"node:module";import s from"node:fs/promises";import c,{basename as l}from"node:path";import u from"node:crypto";import d from"node:fs";function f(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}async function p(e){let t;try{t=await s.lstat(e)}catch(e){if(f(e))return{missing:!0};throw e}if(t.isSymbolicLink()||!t.isFile())throw Error(`path required`);return{missing:!1,stat:t}}function m(e){try{d.mkdirSync(e,{recursive:!0})}catch{}return e}function ee(e){return e.trim().replace(/^[./]+/,``).replace(/\\/g,`/`)}function h(e){let t=ee(e);return t?t===`MEMORY.md`||t===`memory.md`?!0:t.startsWith(`memory/`):!1}async function g(e,t){let n=await s.readdir(e,{withFileTypes:!0});for(let r of n){let n=c.join(e,r.name);if(!r.isSymbolicLink()){if(r.isDirectory()){await g(n,t);continue}r.isFile()&&r.name.endsWith(`.md`)&&t.push(n)}}}async function _(e){let t=[],n=c.join(e,`MEMORY.md`),r=c.join(e,`memory.md`),i=c.join(e,`memory`),a=async e=>{try{let n=await s.lstat(e);if(n.isSymbolicLink()||!n.isFile()||!e.endsWith(`.md`))return;t.push(e)}catch{}};await a(n),await a(r);try{let e=await s.lstat(i);!e.isSymbolicLink()&&e.isDirectory()&&await g(i,t)}catch{}if(t.length<=1)return t;let o=new Set,l=[];for(let e of t){let t=e;try{t=await s.realpath(e)}catch{}o.has(t)||(o.add(t),l.push(e))}return l}function v(e){return u.createHash(`sha256`).update(e).digest(`hex`)}async function te(e,t){let n;try{n=await s.stat(e)}catch(e){if(f(e))return null;throw e}let r;try{r=await s.readFile(e,`utf-8`)}catch(e){if(f(e))return null;throw e}let i=v(r);return{path:c.relative(t,e).replace(/\\/g,`/`),absPath:e,mtimeMs:n.mtimeMs,size:n.size,hash:i}}function ne(e,t){let n=e.split(`
1
+ import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{A as t,C as n,L as r}from"./session-BpKaF-Gk.js";import{o as i,r as a}from"./provider-registry-DPbmbWqS.js";import{createRequire as o}from"node:module";import s from"node:fs/promises";import c,{basename as l}from"node:path";import u from"node:crypto";import d from"node:fs";function f(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}async function p(e){let t;try{t=await s.lstat(e)}catch(e){if(f(e))return{missing:!0};throw e}if(t.isSymbolicLink()||!t.isFile())throw Error(`path required`);return{missing:!1,stat:t}}function m(e){try{d.mkdirSync(e,{recursive:!0})}catch{}return e}function ee(e){return e.trim().replace(/^[./]+/,``).replace(/\\/g,`/`)}function h(e){let t=ee(e);return t?t===`MEMORY.md`||t===`memory.md`?!0:t.startsWith(`memory/`):!1}async function g(e,t){let n=await s.readdir(e,{withFileTypes:!0});for(let r of n){let n=c.join(e,r.name);if(!r.isSymbolicLink()){if(r.isDirectory()){await g(n,t);continue}r.isFile()&&r.name.endsWith(`.md`)&&t.push(n)}}}async function _(e){let t=[],n=c.join(e,`MEMORY.md`),r=c.join(e,`memory.md`),i=c.join(e,`memory`),a=async e=>{try{let n=await s.lstat(e);if(n.isSymbolicLink()||!n.isFile()||!e.endsWith(`.md`))return;t.push(e)}catch{}};await a(n),await a(r);try{let e=await s.lstat(i);!e.isSymbolicLink()&&e.isDirectory()&&await g(i,t)}catch{}if(t.length<=1)return t;let o=new Set,l=[];for(let e of t){let t=e;try{t=await s.realpath(e)}catch{}o.has(t)||(o.add(t),l.push(e))}return l}function v(e){return u.createHash(`sha256`).update(e).digest(`hex`)}async function te(e,t){let n;try{n=await s.stat(e)}catch(e){if(f(e))return null;throw e}let r;try{r=await s.readFile(e,`utf-8`)}catch(e){if(f(e))return null;throw e}let i=v(r);return{path:c.relative(t,e).replace(/\\/g,`/`),absPath:e,mtimeMs:n.mtimeMs,size:n.size,hash:i}}function ne(e,t){let n=e.split(`
2
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
3
  `),r=e.lineNo,i=t.lineNo;a.push({startLine:r,endLine:i,text:n,hash:v(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 re(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 ie(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))}async function b(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)}}}const x=o(import.meta.url);function ae(){return globalThis.Bun!==void 0}function oe(){try{return x(`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 se=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)}},ce=class{db;constructor(e,t){let n=x(`bun:sqlite`);this.db=new(n.Database??n.default?.Database)(e)}exec(e){this.db.run(e)}prepare(e){return new se(this.db.prepare(e))}loadExtension(e){this.db.loadExtension(e)}close(){this.db.close()}},le=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)}},ue=class{db;constructor(e,t){let{DatabaseSync:n}=oe();this.db=new n(e,{allowExtension:t?.allowExtension})}exec(e){this.db.exec(e)}prepare(e){return new le(this.db.prepare(e))}loadExtension(e){this.db.loadExtension(e)}close(){this.db.close()}};function S(e,t){return ae()?new ce(e,t):new ue(e,t)}function de(e){return(e.toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[]).filter(Boolean)}function fe(e){return u.createHash(`sha256`).update(e).digest().readUInt32BE(0)}function C(e,t=384){let n=Array(t).fill(0),r=de(e);if(r.length===0)return n;for(let e of r){let r=fe(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 w(e){let t=e?.model?.trim()||`mock-embedding-v1`,n=e?.dimensions??384;return{id:`external-mock`,model:t,embedQuery:async e=>C(e,n),embedBatch:async e=>e.map(e=>C(e,n))}}const T={enabled:!1,lambda:.7};function E(e){let t=e.toLowerCase().match(/[a-z0-9_]+/g)??[];return new Set(t)}function pe(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 me(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=pe(i,n.get(e.id)??E(e.content));t>r&&(r=t)}return r}function he(e,t,n){return n*e-(1-n)*t}function ge(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=he(l(n.score),me(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 _e(e,t={}){if(e.length===0)return e;let n=new Map;return ge(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 ve(e){return!Number.isFinite(e)||e<=0?0:Math.LN2/e}function ye(e){let t=ve(e.halfLifeDays),n=Math.max(0,e.ageInDays);return t<=0||!Number.isFinite(n)?1:Math.exp(-t*n)}function be(e){return e.score*ye(e)}function xe(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 Se(e){let t=e.replaceAll(`\\`,`/`).replace(/^\.\//,``);return t===`MEMORY.md`||t===`memory.md`?!0:t.startsWith(`memory/`)?!O.test(t):!1}async function Ce(e){let t=xe(e.filePath);if(t)return t;if(e.source===`memory`&&Se(e.filePath)||!e.memoryRoot)return null;let n=c.isAbsolute(e.filePath)?e.filePath:c.resolve(e.memoryRoot,e.filePath);try{let e=await s.stat(n);return Number.isFinite(e.mtimeMs)?new Date(e.mtimeMs):null}catch{return null}}function k(e,t){return Math.max(0,t-e.getTime())/864e5}async function A(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=Ce({filePath:i.path,source:i.source,memoryRoot:e.memoryRoot}),r.set(a,o));let s=await o;if(!s)return i;let c=be({score:i.score,ageInDays:k(s,n),halfLifeDays:t.halfLifeDays});return{...i,score:c}}))}function we(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 Te(e){return 1/(1+(Number.isFinite(e)?Math.max(0,e):999))}async function Ee(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 A({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?_e(n,r):n}function De(e){e.db.exec(`
4
4
  CREATE TABLE IF NOT EXISTS meta (
@@ -46,10 +46,10 @@ import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{A as t,C as n,L as r}f
46
46
  `);for(let e=0;e<d.length;e+=1){let t=d[e]?.trim();if(t)try{let n=JSON.parse(t),r=n.role??`unknown`,i=Ne(n.content);if(!i)continue;let a=i.split(`
47
47
  `);for(let t of a)l.push(`[${r}] ${t}`),u.push(e+1)}catch{}}let p=l.join(`
48
48
  `),m=v(p);return{path:c.join(n(i),P(e,t,i)).replace(/\\/g,`/`),absPath:t,mtimeMs:a.mtimeMs,size:a.size,hash:m,content:p,lineMap:u}}const F=`chunks_vec`,I=`chunks_fts`,L=`embedding_cache`,R=`memory_index_meta_v1`,z=3e4;function Fe(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 B=new Map,Ie=[`database disk image is malformed`,`database disk image malformed`,`file is not a database`,`database disk image is corrupt`,`sqlite_corrupt`];function V(e){let t=`${typeof e==`object`&&e&&`code`in e?String(e.code??``).toLowerCase():``} ${e instanceof Error?e.message:String(e)}`.toLowerCase();return Ie.some(e=>t.includes(e))}function Le(e){let t=`${e}.corrupt-${new Date().toISOString().replace(/[:.]/g,`-`)}`,n=!1;for(let r of[``,`-wal`,`-shm`]){let i=`${e}${r}`,a=`${t}${r}`;try{if(!d.existsSync(i))continue;d.renameSync(i,a),n=!0}catch{try{d.rmSync(i,{force:!0}),n=!0}catch{}}}return n?t:null}function Re(e,t){let r=n(t.store.sessionStoreName),i=[...t.sources].sort().join(`,`),a=t.experimental.sessionMemory?`sessions-on`:`sessions-off`,o=t.store.vector.enabled?`vector-on`:`vector-off`;return[e,`store=${r}`,`sources=${i}`,a,o].join(`::`)}function H(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 U=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 r=c.join(t,`.aimax`),i=H(N,n),a=Re(r,i),o=B.get(a);if(o)return n&&o.applyConfig(n),o;let s=new e(t,r,i);return B.set(a,s),s}static disposeForDataDir(e){let t=c.join(e,`.aimax`),n=0;for(let[e,r]of B.entries())e.startsWith(`${t}::`)&&(r.dispose(),B.delete(e),n+=1);return n}static disposeAll(){let e=0;for(let[t,n]of B.entries())n.dispose(),B.delete(t),e+=1;return e}constructor(e,t,r){this.dataDir=e,this.memoryRoot=t,this.storePath=c.join(t,`.index.sqlite`),this.config=H(N,r),this.sessionStoreName=n(this.config.store.sessionStoreName),this.provider=w(),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.openRecoveredDatabase(),this.ensureWatcher(),this.ensureSessionListener(),this.dirty=!0}applyConfig(e){this.config=H(this.config,e),this.sessionStoreName=n(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)}dispose(){this.watchTimer&&=(clearTimeout(this.watchTimer),null),this.sessionWatchTimer&&=(clearTimeout(this.sessionWatchTimer),null);for(let e of this.watchers.splice(0))try{e.close()}catch{}this.sessionPendingFiles.clear(),this.sessionsDirtyFiles.clear(),this.sessionDeltas.clear();try{this.db.close()}catch{}}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 ${L}`).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 Ee({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 p(t)).missing)return{text:``,path:n};let r;try{r=await s.readFile(t,`utf-8`)}catch(e){if(f(e))return{text:``,path:n};throw e}if(!e.from&&!e.lines)return{text:r,path:n};let i=r.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 B=new Map,Ie=[`database disk image is malformed`,`database disk image malformed`,`file is not a database`,`database disk image is corrupt`,`sqlite_corrupt`];function V(e){let t=`${typeof e==`object`&&e&&`code`in e?String(e.code??``).toLowerCase():``} ${e instanceof Error?e.message:String(e)}`.toLowerCase();return Ie.some(e=>t.includes(e))}function Le(e){let t=`${e}.corrupt-${new Date().toISOString().replace(/[:.]/g,`-`)}`,n=!1;for(let r of[``,`-wal`,`-shm`]){let i=`${e}${r}`,a=`${t}${r}`;try{if(!d.existsSync(i))continue;d.renameSync(i,a),n=!0}catch{try{d.rmSync(i,{force:!0}),n=!0}catch{}}}return n?t:null}function Re(e,t){let r=n(t.store.sessionStoreName),i=[...t.sources].sort().join(`,`),a=t.experimental.sessionMemory?`sessions-on`:`sessions-off`,o=t.store.vector.enabled?`vector-on`:`vector-off`;return[e,`store=${r}`,`sources=${i}`,a,o].join(`::`)}function H(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 U=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 r=c.join(t,`.aimax`),i=H(N,n),a=Re(r,i),o=B.get(a);if(o)return n&&o.applyConfig(n),o;let s=new e(t,r,i);return B.set(a,s),s}static disposeForDataDir(e){let t=c.join(e,`.aimax`),n=0;for(let[e,r]of B.entries())e.startsWith(`${t}::`)&&(r.dispose(),B.delete(e),n+=1);return n}static disposeAll(){let e=0;for(let[t,n]of B.entries())n.dispose(),B.delete(t),e+=1;return e}constructor(e,t,r){this.dataDir=e,this.memoryRoot=t,this.storePath=c.join(t,`.index.sqlite`),this.config=H(N,r),this.sessionStoreName=n(this.config.store.sessionStoreName),this.provider=w(),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.openRecoveredDatabase(),this.ensureWatcher(),this.dirty=!0}applyConfig(e){this.config=H(this.config,e),this.sessionStoreName=n(this.config.store.sessionStoreName),this.applyEmbeddingProvider(),this.vector.enabled=this.config.store.vector.enabled,this.vector.extensionPath=this.config.store.vector.extensionPath,this.ensureWatcher()}warmSession(){this.config.sync.onSessionStart&&this.sync({reason:`session-start`}).catch(()=>{})}noteSessionUpdate(e){this.scheduleSessionDirty(e)}dispose(){this.watchTimer&&=(clearTimeout(this.watchTimer),null),this.sessionWatchTimer&&=(clearTimeout(this.sessionWatchTimer),null);for(let e of this.watchers.splice(0))try{e.close()}catch{}this.sessionPendingFiles.clear(),this.sessionsDirtyFiles.clear(),this.sessionDeltas.clear();try{this.db.close()}catch{}}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 ${L}`).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 Ee({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 p(t)).missing)return{text:``,path:n};let r;try{r=await s.readFile(t,`utf-8`)}catch(e){if(f(e))return{text:``,path:n};throw e}if(!e.from&&!e.lines)return{text:r,path:n};let i=r.split(`
50
50
  `),a=Math.max(1,e.from??1),o=Math.max(1,e.lines??i.length);return{text:i.slice(a-1,a-1+o).join(`
51
51
  `),path:n}}async replaceFile(e){let{absPath:t}=this.resolveMemoryFilePath(e.relPath);await s.mkdir(c.dirname(t),{recursive:!0}),await s.writeFile(t,e.content,`utf-8`),this.dirty=!0,await this.syncAndPostCheck(`replace`)}async deleteFile(e){let{absPath:t}=this.resolveMemoryFilePath(e);try{await s.unlink(t)}catch(e){if(f(e))return;throw e}this.dirty=!0,await this.syncAndPostCheck(`delete`)}async appendToMemory(e){let t=this.memoryRoot;await s.mkdir(t,{recursive:!0});let n=c.join(t,`MEMORY.md`),r=e.endsWith(`
52
- `)?e:`${e}\n`;await s.appendFile(n,r,`utf-8`),this.dirty=!0,await this.syncAndPostCheck(`append`)}openDatabase(){return m(c.dirname(this.storePath)),S(this.storePath,{allowExtension:this.vector.enabled})}openRecoveredDatabase(){let e=null;try{return e=this.openDatabase(),this.db=e,this.ensureSchema(),e}catch(t){try{e?.close()}catch{}if(!V(t))throw t;Le(this.storePath),e=this.openDatabase(),this.db=e,this.ftsAvailable=!1,this.ftsError=void 0,this.vector.available=null,this.vector.dims=void 0;try{this.ensureSchema()}catch(t){try{e.close()}catch{}throw t}return this.searchFallbackOnly=!0,e}}ensureSchema(){let e=De({db:this.db,embeddingCacheTable:L,ftsTable:I,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(),z,`sqlite-vec load timed out after ${Math.round(z/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 b({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 ${F} 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 ${F}`)}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=[c.join(this.memoryRoot,`MEMORY.md`),c.join(this.memoryRoot,`memory.md`),c.join(this.memoryRoot,`memory`)],t=()=>{this.dirty=!0,this.scheduleWatchSync()};for(let n of e)try{let e=d.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=d.watch(e,{recursive:!0},(t,n)=>{if(!n||!n.endsWith(`transcript.jsonl`))return;let r=c.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 s.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 a=Math.max(0,r-i.lastSize);return a===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+=a,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 s.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 v(JSON.stringify({provider:this.provider.id,model:this.provider.model}))}resolveMemoryFilePath(e){let t=e.trim();if(!t)throw Error(`path required`);let n=c.isAbsolute(t)?c.resolve(t):c.resolve(this.memoryRoot,t),r=c.relative(this.memoryRoot,n).replace(/\\/g,`/`);if(!(r.length>0&&!r.startsWith(`..`)&&!c.isAbsolute(r)&&h(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=i({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=w(),this.embeddingProviderId=void 0,this.providerKey=this.computeProviderKey(),this.dirty=!0)}readMeta(){let e=this.db.prepare(`SELECT value FROM meta WHERE key = ?`).get(R);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(R,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 ${L}\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 ${L} (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=ne(t.content??await s.readFile(e.absPath,`utf-8`),{tokens:this.config.chunkTokens,overlap:this.config.chunkOverlap}).filter(e=>e.text.trim().length>0);t.source===`sessions`&&re(n,t.lineMap);let r=await this.embedChunks(n),i=r.find(e=>e.length>0),a=i?await this.ensureVectorReady(i.length):!1,o=Date.now();if(a)try{this.db.prepare(`DELETE FROM ${F} 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 ${I} 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 s=n[i],c=r[i]??[],l=v(`${t.source}:${e.path}:${s.startLine}:${s.endLine}:${s.hash}:${this.provider.model}`);if(this.db.prepare(`INSERT INTO chunks (id, path, source, start_line, end_line, hash, model, text, embedding, updated_at)
52
+ `)?e:`${e}\n`;await s.appendFile(n,r,`utf-8`),this.dirty=!0,await this.syncAndPostCheck(`append`)}openDatabase(){return m(c.dirname(this.storePath)),S(this.storePath,{allowExtension:this.vector.enabled})}openRecoveredDatabase(){let e=null;try{return e=this.openDatabase(),this.db=e,this.ensureSchema(),e}catch(t){try{e?.close()}catch{}if(!V(t))throw t;Le(this.storePath),e=this.openDatabase(),this.db=e,this.ftsAvailable=!1,this.ftsError=void 0,this.vector.available=null,this.vector.dims=void 0;try{this.ensureSchema()}catch(t){try{e.close()}catch{}throw t}return this.searchFallbackOnly=!0,e}}ensureSchema(){let e=De({db:this.db,embeddingCacheTable:L,ftsTable:I,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(),z,`sqlite-vec load timed out after ${Math.round(z/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 b({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 ${F} 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 ${F}`)}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=[c.join(this.memoryRoot,`MEMORY.md`),c.join(this.memoryRoot,`memory.md`),c.join(this.memoryRoot,`memory`)],t=()=>{this.dirty=!0,this.scheduleWatchSync()};for(let n of e)try{let e=d.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))}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 s.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 a=Math.max(0,r-i.lastSize);return a===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+=a,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 s.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 v(JSON.stringify({provider:this.provider.id,model:this.provider.model}))}resolveMemoryFilePath(e){let t=e.trim();if(!t)throw Error(`path required`);let n=c.isAbsolute(t)?c.resolve(t):c.resolve(this.memoryRoot,t),r=c.relative(this.memoryRoot,n).replace(/\\/g,`/`);if(!(r.length>0&&!r.startsWith(`..`)&&!c.isAbsolute(r)&&h(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=i({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=w(),this.embeddingProviderId=void 0,this.providerKey=this.computeProviderKey(),this.dirty=!0)}readMeta(){let e=this.db.prepare(`SELECT value FROM meta WHERE key = ?`).get(R);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(R,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 ${L}\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 ${L} (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=ne(t.content??await s.readFile(e.absPath,`utf-8`),{tokens:this.config.chunkTokens,overlap:this.config.chunkOverlap}).filter(e=>e.text.trim().length>0);t.source===`sessions`&&re(n,t.lineMap);let r=await this.embedChunks(n),i=r.find(e=>e.length>0),a=i?await this.ensureVectorReady(i.length):!1,o=Date.now();if(a)try{this.db.prepare(`DELETE FROM ${F} 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 ${I} 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 s=n[i],c=r[i]??[],l=v(`${t.source}:${e.path}:${s.startLine}:${s.endLine}:${s.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
53
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
54
54
  ON CONFLICT(id) DO UPDATE SET
55
55
  hash=excluded.hash,
@@ -1 +1 @@
1
- import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{E as t}from"./session-CvZsdTZJ.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
+ import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{E as t}from"./session-BpKaF-Gk.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{E as t,P as n}from"./session-CvZsdTZJ.js";import{t as r}from"./goal-events-BtFriEK5.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({GOAL_OBJECTIVE_REF:()=>u,GoalObjectiveResolutionError:()=>l,deleteGoal:()=>v,goalDir:()=>d,goalObjectiveMdPath:()=>p,goalPath:()=>f,mirrorGoalStatusToSession:()=>y,readGoal:()=>m,resolveGoalObjective:()=>h,updateGoal:()=>_,writeGoal:()=>g}),l=class extends Error{constructor(e,t){super(e,t),this.name=`GoalObjectiveResolutionError`}};const u=`goal/objective.md`;function d(e,n,r){return o.join(t(e,n,r),`goal`)}function f(e,t,n){return o.join(d(e,t,n),`goal.json`)}function p(e,t,n){return o.join(d(e,t,n),`objective.md`)}async function m(e,t,n){let r=f(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 h(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 g(e,t,n,o){let c=await m(e,t,o),l=n.objective.trim(),g=new Date().toISOString(),_={...n,objective:l,goalId:n.goalId??s(),createdAt:n.createdAt??g,updatedAt:n.updatedAt??g};c&&((await h(e,t,c,o)).trim()===l?c.pendingObjectiveUpdatedNotice&&(_.pendingObjectiveUpdatedNotice=!0):_.pendingObjectiveUpdatedNotice=!0);let v=d(e,t,o);await a.mkdir(v,{recursive:!0});let b;if(_.objective.length>i)b=_.objective,_.objective=_.objective.slice(0,200)+`...`,_.objectiveRef=u;else{delete _.objectiveRef;try{await a.unlink(p(e,t,o))}catch(e){if(e.code!==`ENOENT`)throw e}}if(b!==void 0){let n=p(e,t,o),r=n+`.tmp`;await a.writeFile(r,b,`utf-8`),await a.rename(r,n)}let x=f(e,t,o),S=x+`.tmp`;return await a.writeFile(S,JSON.stringify(_,null,2),`utf-8`),await a.rename(S,x),await y(e,t,_.status,o),await r(e,t,{goalId:_.goalId,action:c?`replaced`:`created`,status:_.status,source:o?.eventSource??`store`,detail:c?{previousGoalId:c.goalId}:void 0},o),_}async function _(e,t,n,i){let o=await m(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=f(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 y(e,t,s.status,i);let u=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:u,status:s.status,source:i?.eventSource??`store`,detail:{fields:Object.keys(n)}},i),s}async function v(e,t,n){let i=await m(e,t,n);return i?(await r(e,t,{goalId:i.goalId,action:`deleted`,status:null,source:n?.eventSource??`store`},n),await a.rm(d(e,t,n),{recursive:!0,force:!0}),await y(e,t,null,n),!0):!1}async function y(e,t,r,i){await n(e,t,{goalStatus:r},i)}export{c as a,h as c,f as i,_ as l,d as n,y as o,p as r,m as s,v as t,g as u};
1
+ import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{E as t,P as n}from"./session-BpKaF-Gk.js";import{t as r}from"./goal-events-CocRykqc.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({GOAL_OBJECTIVE_REF:()=>u,GoalObjectiveResolutionError:()=>l,deleteGoal:()=>v,goalDir:()=>d,goalObjectiveMdPath:()=>p,goalPath:()=>f,mirrorGoalStatusToSession:()=>y,readGoal:()=>m,resolveGoalObjective:()=>h,updateGoal:()=>_,writeGoal:()=>g}),l=class extends Error{constructor(e,t){super(e,t),this.name=`GoalObjectiveResolutionError`}};const u=`goal/objective.md`;function d(e,n,r){return o.join(t(e,n,r),`goal`)}function f(e,t,n){return o.join(d(e,t,n),`goal.json`)}function p(e,t,n){return o.join(d(e,t,n),`objective.md`)}async function m(e,t,n){let r=f(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 h(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 g(e,t,n,o){let c=await m(e,t,o),l=n.objective.trim(),g=new Date().toISOString(),_={...n,objective:l,goalId:n.goalId??s(),createdAt:n.createdAt??g,updatedAt:n.updatedAt??g};c&&((await h(e,t,c,o)).trim()===l?c.pendingObjectiveUpdatedNotice&&(_.pendingObjectiveUpdatedNotice=!0):_.pendingObjectiveUpdatedNotice=!0);let v=d(e,t,o);await a.mkdir(v,{recursive:!0});let b;if(_.objective.length>i)b=_.objective,_.objective=_.objective.slice(0,200)+`...`,_.objectiveRef=u;else{delete _.objectiveRef;try{await a.unlink(p(e,t,o))}catch(e){if(e.code!==`ENOENT`)throw e}}if(b!==void 0){let n=p(e,t,o),r=n+`.tmp`;await a.writeFile(r,b,`utf-8`),await a.rename(r,n)}let x=f(e,t,o),S=x+`.tmp`;return await a.writeFile(S,JSON.stringify(_,null,2),`utf-8`),await a.rename(S,x),await y(e,t,_.status,o),await r(e,t,{goalId:_.goalId,action:c?`replaced`:`created`,status:_.status,source:o?.eventSource??`store`,detail:c?{previousGoalId:c.goalId}:void 0},o),_}async function _(e,t,n,i){let o=await m(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=f(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 y(e,t,s.status,i);let u=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:u,status:s.status,source:i?.eventSource??`store`,detail:{fields:Object.keys(n)}},i),s}async function v(e,t,n){let i=await m(e,t,n);return i?(await r(e,t,{goalId:i.goalId,action:`deleted`,status:null,source:n?.eventSource??`store`},n),await a.rm(d(e,t,n),{recursive:!0,force:!0}),await y(e,t,null,n),!0):!1}async function y(e,t,r,i){await n(e,t,{goalStatus:r},i)}export{c as a,h as c,f as i,_ as l,d as n,y as o,p as r,m as s,v as t,g as u};
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { C as AgentsConfig, S as AgentModelConfig, _ as saveAgentsConfig, a as listAgents, b as AgentBinding, 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 updateAgent, x as AgentConfig, y as updateAgentIdentity } from "./index-BNCxlrCH.js";
2
- import { $ as loadSkills, $n as MemoryChangeSource, $t as PluginManifestRegistry, A as AgentRuntimePolicyInput, An as PluginHookContextEvent, At as loadArtifactOperations, B as filterToolsForAgent, Bn as PluginHookName, Bt as sessionDir, C as TranscriptEntry, Cn as PluginHookBeforeModelResolveResult, Ct as createSession, D as AgentDefinitionsStats, Dn as PluginHookBeforeProviderRequestResult, Dt as inspectSession, E as AgentDefinitionsContext, En as PluginHookBeforeProviderRequestEvent, Et as exportSession, F as agentVisibility, Fn as PluginHookInputEvent, Ft as loadTranscript, G as resolveAgentDefinitionsContext, Gn as PluginHookSessionEndEvent, Gt as transcriptPath, H as loadAgentDefinitionsFromDir, Hn as PluginHookRegistry, Ht as sessionsDir, I as buildAgentDelegationPrompt, In as PluginHookInputResult, It as metadataPath, J as SkillDirectory, Jn as PluginHookToolResultEvent, Jt as PluginEntryConfig, K as scanAgentDefinitions, Kn as PluginHookSessionResetEvent, Kt as updateSessionMetadata, L as buildAgentTaskPrompt, Ln as PluginHookLlmInputEvent, Lt as normalizeSessionStoreName, M as AgentVisibility, Mn as PluginHookDreamGateEvent, Mt as loadSessionContextSnapshot, N as SYSTEM_AGENTS_DIR, Nn as PluginHookDreamGateResult, Nt as loadSessionMetadata, O as AgentDirectoryCandidate, On as PluginHookBeforeToolCallEvent, Ot as listSessionSummaries, P as agentDirCandidates, Pn as PluginHookHandlerMap, Pt as loadSystemPromptSnapshot, Q as loadSkillView, Qn as ReadonlyTranscriptSessionAdapter, Qt as validatePluginsConfig, R as createAgentDefinitionsContext, Rn as PluginHookLlmOutputEvent, Rt as rewriteTranscript, S as ThinkingLevel, Sn as PluginHookBeforeModelResolveEvent, St as contextSnapshotPath, T as AgentDefinition, Tn as PluginHookBeforePromptBuildResult, Tt as ensureSession, U as parseAgentDefinition, Un as PluginHookResourcesDiscoverEvent, Ut as systemPromptSnapshotPath, V as findAgentDefinition, Vn as PluginHookRegistration, Vt as sessionMemoryPath, W as publicAgentDefinitions, Wn as PluginHookResourcesDiscoverResult, Wt as toolResultsDir, X as buildSkillsPrompt, Xn as PluginHookTurnEndEvent, Xt as PluginsConfigValidationResult, Y as SkillViewResult, Yn as PluginHookToolResultResult, Yt as PluginsConfig, Z as findSkillByName, Zn as PluginHookTurnStartEvent, Zt as normalizePluginsConfig, _ as CallbackPayload, _n as PluginHookAssistantMessageEndEvent, _t as appendArtifactOperation, a as PluginToolOptions, an as PluginKind, ar as MemorySearchOptions, at as ArtifactOpInput, b as PiExtensionDialogBridge, bn as PluginHookBeforeCompactionEvent, bt as artifactsPath, c as PluginUiToolOptions, cn as PluginOrigin, cr as MemoryRebuildSummary, ct as ArtifactOperationName, d as UiToolOptions, dn as PluginHookAfterCompactionEvent, dr as AgentLogEntry, dt as DEFAULT_SESSION_STORE_NAME, en as loadPluginManifestRegistry, er as MemoryChangedEvent, et as loadSkillsFromDirs, f as createUiTool, fn as PluginHookAfterPromptBuildEvent, fr as OnLogCallback, ft as MAX_ARTIFACT_CONTENT_CHARS, g as AgentRunResult, gn as PluginHookAgentStartEvent, gt as SessionPathOptions, h as AgentRunParams, hn as PluginHookAgentEndEvent, ht as SessionMetadataUpdate, in as PluginDiscoveryResult, ir as MemoryProviderFactory, it as LlmApiFormat, j as AgentScanOptions, jn as PluginHookContextResult, jt as loadCronExecutionRecords, k as AgentRuntimePolicy, kn as PluginHookBeforeToolCallResult, kt as listSessions, l as RegisteredPluginTool, ln as RunEventDispatcher, lr as MemorySearchResult$1, lt as ArtifactOperationType, m as AgentProgressEvent$2, mn as PluginHookAgentContext, mt as SessionInspection, nn as PluginConfigUiHint, nr as MemoryProvider, nt as skillsDir, o as PluginToolRegistry, on as PluginManifest, or as MemoryIndexManager, ot as ArtifactOperation, p as defaultUiToolInputSchema, pn as PluginHookAfterToolCallEvent, pt as SessionExport, q as Skill, qn as PluginHookSessionStartEvent, qt as NormalizedPluginsConfig, rn as PluginDiagnostic, rr as MemoryProviderContext, rt as TopicSegmentationConfig, s as PluginUiToolDescriptor, sn as PluginManifestLoadResult, sr as MemoryProviderStatus, st as ArtifactOperationInput, tn as PluginCandidate, tr as MemoryChangedHandler, tt as loadSkillsWithPluginDirs, u as UiToolInputSchema, un as PluginExecutionRuntime, ur as ToolLoopDetectionConfig, ut as CronExecutionRecord, v as Channel, vn as PluginHookBeforeAgentStartEvent, vt as appendCronExecutionRecord, w as AgentConfigSource, wn as PluginHookBeforePromptBuildEvent, wt as cronExecutionsPath, x as SubagentContext, xn as PluginHookBeforeCompactionResult, xt as collapseLogPath, y as CompactionEntry, yn as PluginHookBeforeAgentStartResult, yt as appendTranscriptEntry, z as filterSkillsForAgent, zn as PluginHookMemoryChangedEvent, zt as saveSessionMetadata } from "./loader-D9_1WNPg.js";
3
- import { C as createPluginProgressEmitter, S as PluginProgressEmitter, T as createPluginRuntime, _ as resetEmbeddingProviderRegistryForTests, a as PluginSystemOptions, b as PluginRuntimeContext, c as preloadPluginSystem, d as PluginRegistry, f as loadPlugins, g as registerEmbeddingProvider, h as EmbeddingProviderRegistration, i as PluginSystem, l as PluginApi, m as EmbeddingProviderFactory, n as SystemWarmState, o as getPluginSystem, p as EmbeddingProviderContext, r as prepareSystemRuntime, s as initializePluginSystem, t as PrepareSystemRuntimeOptions, u as PluginRecord, v as resolveEmbeddingProvider, w as PluginRuntime, x as PluginCustomProgressInput, y as EmbeddingProvider } from "./system-runtime-Bi5ESko9.js";
2
+ import { $ as loadSkills, $n as MemoryChangeSource, $t as PluginManifestRegistry, A as AgentRuntimePolicyInput, An as PluginHookContextEvent, At as loadArtifactOperations, B as filterToolsForAgent, Bn as PluginHookName, Bt as sessionDir, C as TranscriptEntry, Cn as PluginHookBeforeModelResolveResult, Ct as createSession, D as AgentDefinitionsStats, Dn as PluginHookBeforeProviderRequestResult, Dt as inspectSession, E as AgentDefinitionsContext, En as PluginHookBeforeProviderRequestEvent, Et as exportSession, F as agentVisibility, Fn as PluginHookInputEvent, Ft as loadTranscript, G as resolveAgentDefinitionsContext, Gn as PluginHookSessionEndEvent, Gt as transcriptPath, H as loadAgentDefinitionsFromDir, Hn as PluginHookRegistry, Ht as sessionsDir, I as buildAgentDelegationPrompt, In as PluginHookInputResult, It as metadataPath, J as SkillDirectory, Jn as PluginHookToolResultEvent, Jt as PluginEntryConfig, K as scanAgentDefinitions, Kn as PluginHookSessionResetEvent, Kt as updateSessionMetadata, L as buildAgentTaskPrompt, Ln as PluginHookLlmInputEvent, Lt as normalizeSessionStoreName, M as AgentVisibility, Mn as PluginHookDreamGateEvent, Mt as loadSessionContextSnapshot, N as SYSTEM_AGENTS_DIR, Nn as PluginHookDreamGateResult, Nt as loadSessionMetadata, O as AgentDirectoryCandidate, On as PluginHookBeforeToolCallEvent, Ot as listSessionSummaries, P as agentDirCandidates, Pn as PluginHookHandlerMap, Pt as loadSystemPromptSnapshot, Q as loadSkillView, Qn as ReadonlyTranscriptSessionAdapter, Qt as validatePluginsConfig, R as createAgentDefinitionsContext, Rn as PluginHookLlmOutputEvent, Rt as rewriteTranscript, S as ThinkingLevel, Sn as PluginHookBeforeModelResolveEvent, St as contextSnapshotPath, T as AgentDefinition, Tn as PluginHookBeforePromptBuildResult, Tt as ensureSession, U as parseAgentDefinition, Un as PluginHookResourcesDiscoverEvent, Ut as systemPromptSnapshotPath, V as findAgentDefinition, Vn as PluginHookRegistration, Vt as sessionMemoryPath, W as publicAgentDefinitions, Wn as PluginHookResourcesDiscoverResult, Wt as toolResultsDir, X as buildSkillsPrompt, Xn as PluginHookTurnEndEvent, Xt as PluginsConfigValidationResult, Y as SkillViewResult, Yn as PluginHookToolResultResult, Yt as PluginsConfig, Z as findSkillByName, Zn as PluginHookTurnStartEvent, Zt as normalizePluginsConfig, _ as CallbackPayload, _n as PluginHookAssistantMessageEndEvent, _t as appendArtifactOperation, a as PluginToolOptions, an as PluginKind, ar as MemorySearchOptions, at as ArtifactOpInput, b as PiExtensionDialogBridge, bn as PluginHookBeforeCompactionEvent, bt as artifactsPath, c as PluginUiToolOptions, cn as PluginOrigin, cr as MemoryRebuildSummary, ct as ArtifactOperationName, d as UiToolOptions, dn as PluginHookAfterCompactionEvent, dr as AgentLogEntry, dt as DEFAULT_SESSION_STORE_NAME, en as loadPluginManifestRegistry, er as MemoryChangedEvent, et as loadSkillsFromDirs, f as createUiTool, fn as PluginHookAfterPromptBuildEvent, fr as OnLogCallback, ft as MAX_ARTIFACT_CONTENT_CHARS, g as AgentRunResult, gn as PluginHookAgentStartEvent, gt as SessionPathOptions, h as AgentRunParams, hn as PluginHookAgentEndEvent, ht as SessionMetadataUpdate, in as PluginDiscoveryResult, ir as MemoryProviderFactory, it as LlmApiFormat, j as AgentScanOptions, jn as PluginHookContextResult, jt as loadCronExecutionRecords, k as AgentRuntimePolicy, kn as PluginHookBeforeToolCallResult, kt as listSessions, l as RegisteredPluginTool, ln as RunEventDispatcher, lr as MemorySearchResult$1, lt as ArtifactOperationType, m as AgentProgressEvent$2, mn as PluginHookAgentContext, mt as SessionInspection, nn as PluginConfigUiHint, nr as MemoryProvider, nt as skillsDir, o as PluginToolRegistry, on as PluginManifest, or as MemoryIndexManager, ot as ArtifactOperation, p as defaultUiToolInputSchema, pn as PluginHookAfterToolCallEvent, pt as SessionExport, q as Skill, qn as PluginHookSessionStartEvent, qt as NormalizedPluginsConfig, rn as PluginDiagnostic, rr as MemoryProviderContext, rt as TopicSegmentationConfig, s as PluginUiToolDescriptor, sn as PluginManifestLoadResult, sr as MemoryProviderStatus, st as ArtifactOperationInput, tn as PluginCandidate, tr as MemoryChangedHandler, tt as loadSkillsWithPluginDirs, u as UiToolInputSchema, un as PluginExecutionRuntime, ur as ToolLoopDetectionConfig, ut as CronExecutionRecord, v as Channel, vn as PluginHookBeforeAgentStartEvent, vt as appendCronExecutionRecord, w as AgentConfigSource, wn as PluginHookBeforePromptBuildEvent, wt as cronExecutionsPath, x as SubagentContext, xn as PluginHookBeforeCompactionResult, xt as collapseLogPath, y as CompactionEntry, yn as PluginHookBeforeAgentStartResult, yt as appendTranscriptEntry, z as filterSkillsForAgent, zn as PluginHookMemoryChangedEvent, zt as saveSessionMetadata } from "./loader-CGp_n4m8.js";
3
+ import { C as createPluginProgressEmitter, S as PluginProgressEmitter, T as createPluginRuntime, _ as resetEmbeddingProviderRegistryForTests, a as PluginSystemOptions, b as PluginRuntimeContext, c as preloadPluginSystem, d as PluginRegistry, f as loadPlugins, g as registerEmbeddingProvider, h as EmbeddingProviderRegistration, i as PluginSystem, l as PluginApi, m as EmbeddingProviderFactory, n as SystemWarmState, o as getPluginSystem, p as EmbeddingProviderContext, r as prepareSystemRuntime, s as initializePluginSystem, t as PrepareSystemRuntimeOptions, u as PluginRecord, v as resolveEmbeddingProvider, w as PluginRuntime, x as PluginCustomProgressInput, y as EmbeddingProvider } from "./system-runtime-Bop42Cc_.js";
4
4
  import { AgentCustomProgressEvent, AgentProgressEvent, AgentProgressEvent as AgentProgressEvent$1, AgentTaskItem, AgentTaskStatus, AgentTaskUpdatedEvent, ArtifactRecord, ArtifactRecord as ArtifactRecord$1, CallbackEventPayload, Channel as Channel$1, CollapseSpan, CoreMemoryConfig, GoalStatus, HitlCheckpoint as HitlCheckpoint$1, HitlHistoryEntry, HitlRequest, HitlRequest as HitlRequest$1, HitlResolution, HitlResolution as HitlResolution$1, HitlStatus, HitlToolContext, HitlToolContext as HitlToolContext$1, MemoryCompactionRecallRuntimeState, MemoryRecallRuntimeState, ModelUsageCheckpoint, PausedRunState, PausedRunState as PausedRunState$1, ReadStateRecord, RunResultPayload, SessionContextSnapshot, SessionMemorySnapshot, SessionMetadata, SessionSummary, SnipRecord, ThreadGoal, ToolResultReference, UiToolExtra, UiToolOutputSchema, UiToolPausedState, UiToolRequest, UiToolResult } from "@gencode/shared";
5
5
  import { Agent, AgentMessage, AgentTool } from "@earendil-works/pi-agent-core";
6
6
  import { Message, Type } from "@earendil-works/pi-ai";
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import{A as e,C as t,D as n,E as r,F as i,I as a,L as o,M as s,N as c,O as l,P as u,R as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,j as C,k as w,l as T,m as E,n as D,o as O,p as k,r as A,s as j,t as M,u as N,v as P,w as F,x as I,y as L,z as R}from"./session-CvZsdTZJ.js";import{n as z,t as B}from"./goal-events-BtFriEK5.js";import{c as V,i as H,l as U,n as ee,o as te,r as ne,s as W,t as re,u as G}from"./goal-store-CmMXXTIZ.js";import{A as ie,C as ae,D as K,E as oe,F as se,I as ce,M as le,N as ue,O as de,P as fe,S as pe,T as me,_ as he,a as ge,b as _e,c as ve,d as ye,f as be,g as xe,h as Se,i as Ce,j as we,k as Te,l as Ee,m as De,n as Oe,o as ke,p as Ae,r as je,s as Me,t as Ne,u as Pe,v as Fe,w as Ie,x as Le,y as Re}from"./system-runtime-g4RJ5wzA.js";import{a as ze,c as Be,i as Ve,l as He,o as Ue,r as We,s as Ge,t as Ke,u as qe}from"./default-provider-DchVtHkL.js";import{a as Je,i as Ye,n as Xe,o as Ze,r as Qe,t as $e}from"./provider-registry-DPbmbWqS.js";import"./loader-CkdBGDtW.js";import{t as et}from"./host-BC9sAhdH.js";import{a as tt,i as nt,l as rt,n as it,o as at,r as ot,s as st,t as ct}from"./session-store-BaH2Dvmo.js";import{_ as lt,a as ut,c as dt,d as ft,f as pt,g as mt,h as ht,i as gt,l as _t,m as vt,n as yt,o as bt,p as xt,s as St,t as Ct,u as wt,v as Tt,y as Et}from"./config-DDlWxQf7.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Dt,formatTaskForDisplay as Ot,isHitlExpired as kt,isHitlTool as At}from"@gencode/shared";import q,{readFile as jt}from"node:fs/promises";import J,{join as Mt}from"node:path";import{createHash as Nt,randomBytes as Pt,randomUUID as Ft}from"node:crypto";import It from"node:os";import{spawn as Lt}from"node:child_process";import{TextDecoder as Rt}from"node:util";import zt from"gray-matter";import{Agent as Bt}from"@earendil-works/pi-agent-core";import{AsyncLocalStorage as Vt}from"node:async_hooks";import Ht from"node:fs";import Ut from"openai";import{Type as Y,calculateCost as Wt,clampThinkingLevel as Gt,createAssistantMessageEventStream as Kt,getEnvApiKey as qt,parseStreamingJson as Jt,registerApiProvider as Yt,registerBuiltInApiProviders as Xt,streamSimple as Zt}from"@earendil-works/pi-ai";import{fileURLToPath as Qt}from"node:url";import{isBinaryFile as $t}from"isbinaryfile";var en=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 tn(e,t,n,r,i){let a=await W(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 U(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}const nn=`clarify plan and acceptance`,rn=`补齐后续 task list、每个 task 的验收项和当前下一步`,an={goal:[`目标`,`goal`,`objective`],scope:[`范围`,`scope`,`约束`,`constraints`],steps:[`步骤`,`阶段`,`steps`,`phases`],acceptance:[`完成标准`,`验收`,`验证`,`输出`,`acceptance`,`verification`,`output`,`deliverables`]},on=[`test`,`verify`,`validation`,`pass`,`run `,`npm `,`pnpm `,`pytest`,`通过`,`验证`,`测试`,`输出`,`证明`,`截图`,`日志`,`覆盖`,`回归`];function sn(e){return e.trim().toLowerCase().replace(/[【】\[\]]/g,``)}function cn(e,t){let n=sn(e);return t.some(e=>n===e.toLowerCase()||n.includes(e.toLowerCase()))}function ln(e){let t=e.split(/\r?\n/),n=[];for(let e of t){let t=e.trim();if(!t)continue;let r=t.match(/^(?:[-*•]|\d+[.)])\s+(.+)$/);if(r?.[1]){n.push(r[1].trim());continue}t.length>=8&&n.push(t)}return n.filter(e=>e.length>=4)}function un(e){let t={raw:e.trim()},n=/(?:^|\n)\s*(?:【([^】]+)】|(?:#{1,3}\s*)?([A-Za-z\u4e00-\u9fff][^:\n]{0,30}))\s*[::]\s*/g,r=[],i;for(;(i=n.exec(e))!==null;){let e=(i[1]??i[2]??``).trim();e&&r.push({label:e,start:i.index,contentStart:i.index+i[0].length})}for(let n=0;n<r.length;n+=1){let i=r[n],a=r[n+1],o=e.slice(i.contentStart,a?.start??e.length).trim();for(let[e,n]of Object.entries(an))cn(i.label,n)&&(t[e]=t[e]?`${t[e]}\n${o}`:o)}return{goal:t.goal?.trim()||e.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>=8)||e.trim(),scope:t.scope?.trim()??``,steps:t.steps?ln(t.steps):[],acceptance:t.acceptance?ln(t.acceptance):[],raw:e.trim()}}function dn(e){let t=e.toLowerCase();return on.some(e=>t.includes(e.toLowerCase()))}function fn(e){return e.some(dn)}function pn(e,t){return{id:e,text:t,required:!0}}function mn(e){return{id:e.id,kind:e.kind,title:e.title,required:!0,status:e.status,acceptanceCriteria:e.acceptanceCriteria,acceptanceEvidence:[],evidenceRefs:[],blockedReason:null,updatedAt:e.updatedAt}}function hn(e){return mn({id:`task-1`,kind:`clarify`,title:nn,status:`doing`,acceptanceCriteria:[pn(`ac-1`,rn)],updatedAt:e})}function gn(e,t,n){let r=e.slice(0,5),i=t.length>0?t.map((e,t)=>pn(`ac-${t+1}`,e)):[pn(`ac-1`,`完成:${r[0]}`)];return r.map((e,t)=>mn({id:`task-${t+1}`,kind:`execution`,title:e,status:t===0?`doing`:`todo`,acceptanceCriteria:t===0?i:[pn(`ac-1`,`完成:${e}`)],updatedAt:n}))}function _n(e){let t=new Date().toISOString(),n=un(e),r=n.goal||n.raw,i=n.scope?[n.scope]:[],a=[];if(n.steps.length>=2)return{interpretation:r,assumptions:i,openQuestions:a,tasks:gn(n.steps,n.acceptance,t)};let o=n.acceptance;if(o.length>0&&fn(o))return{interpretation:r,assumptions:i,openQuestions:a,tasks:gn([n.steps[0]??n.goal],o,t)};if(n.raw.length>=40&&fn(ln(n.raw))){let e=ln(n.raw).filter(dn);return{interpretation:r,assumptions:i,openQuestions:a,tasks:gn([n.goal],e,t)}}return{interpretation:r,assumptions:i,openQuestions:a,tasks:[hn(t)]}}function vn(e,t){return`- [${e?`x`:` `}] ${t.id}: ${t.text}`}function yn(e,t){let n=t??new Set(e.acceptanceEvidence);return[`### ${e.id}: ${e.title}`,``,`Status: ${e.status}`,``,`Acceptance Criteria:`,...e.acceptanceCriteria.map(e=>vn(n.has(e.id),e)),``].join(`
1
+ import{A as e,C as t,D as n,E as r,F as i,I as a,L as o,M as s,N as c,O as l,P as u,R as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,j as C,k as w,l as T,m as E,n as D,o as O,p as k,r as A,s as j,t as M,u as N,v as P,w as F,x as I,y as L,z as R}from"./session-BpKaF-Gk.js";import{n as z,t as B}from"./goal-events-CocRykqc.js";import{c as V,i as H,l as U,n as ee,o as te,r as ne,s as W,t as re,u as G}from"./goal-store-M3_Nx3ky.js";import{A as ie,C as ae,D as K,E as oe,F as se,I as ce,M as le,N as ue,O as de,P as fe,S as pe,T as me,_ as he,a as ge,b as _e,c as ve,d as ye,f as be,g as xe,h as Se,i as Ce,j as we,k as Te,l as Ee,m as De,n as Oe,o as ke,p as Ae,r as je,s as Me,t as Ne,u as Pe,v as Fe,w as Ie,x as Le,y as Re}from"./system-runtime-g4RJ5wzA.js";import{a as ze,c as Be,i as Ve,l as He,o as Ue,r as We,s as Ge,t as Ke,u as qe}from"./default-provider-BV9gmV00.js";import{a as Je,i as Ye,n as Xe,o as Ze,r as Qe,t as $e}from"./provider-registry-DPbmbWqS.js";import"./loader-CkdBGDtW.js";import{t as et}from"./host-BC9sAhdH.js";import{a as tt,i as nt,l as rt,n as it,o as at,r as ot,s as st,t as ct}from"./session-store-BwYOp-2K.js";import{_ as lt,a as ut,c as dt,d as ft,f as pt,g as mt,h as ht,i as gt,l as _t,m as vt,n as yt,o as bt,p as xt,s as St,t as Ct,u as wt,v as Tt,y as Et}from"./config-DDlWxQf7.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Dt,formatTaskForDisplay as Ot,isHitlExpired as kt,isHitlTool as At}from"@gencode/shared";import q,{readFile as jt}from"node:fs/promises";import J,{join as Mt}from"node:path";import{createHash as Nt,randomBytes as Pt,randomUUID as Ft}from"node:crypto";import It from"node:os";import{spawn as Lt}from"node:child_process";import{TextDecoder as Rt}from"node:util";import zt from"gray-matter";import{Agent as Bt}from"@earendil-works/pi-agent-core";import{AsyncLocalStorage as Vt}from"node:async_hooks";import Ht from"node:fs";import Ut from"openai";import{Type as Y,calculateCost as Wt,clampThinkingLevel as Gt,createAssistantMessageEventStream as Kt,getEnvApiKey as qt,parseStreamingJson as Jt,registerApiProvider as Yt,registerBuiltInApiProviders as Xt,streamSimple as Zt}from"@earendil-works/pi-ai";import{fileURLToPath as Qt}from"node:url";import{isBinaryFile as $t}from"isbinaryfile";var en=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 tn(e,t,n,r,i){let a=await W(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 U(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}const nn=`clarify plan and acceptance`,rn=`补齐后续 task list、每个 task 的验收项和当前下一步`,an={goal:[`目标`,`goal`,`objective`],scope:[`范围`,`scope`,`约束`,`constraints`],steps:[`步骤`,`阶段`,`steps`,`phases`],acceptance:[`完成标准`,`验收`,`验证`,`输出`,`acceptance`,`verification`,`output`,`deliverables`]},on=[`test`,`verify`,`validation`,`pass`,`run `,`npm `,`pnpm `,`pytest`,`通过`,`验证`,`测试`,`输出`,`证明`,`截图`,`日志`,`覆盖`,`回归`];function sn(e){return e.trim().toLowerCase().replace(/[【】\[\]]/g,``)}function cn(e,t){let n=sn(e);return t.some(e=>n===e.toLowerCase()||n.includes(e.toLowerCase()))}function ln(e){let t=e.split(/\r?\n/),n=[];for(let e of t){let t=e.trim();if(!t)continue;let r=t.match(/^(?:[-*•]|\d+[.)])\s+(.+)$/);if(r?.[1]){n.push(r[1].trim());continue}t.length>=8&&n.push(t)}return n.filter(e=>e.length>=4)}function un(e){let t={raw:e.trim()},n=/(?:^|\n)\s*(?:【([^】]+)】|(?:#{1,3}\s*)?([A-Za-z\u4e00-\u9fff][^:\n]{0,30}))\s*[::]\s*/g,r=[],i;for(;(i=n.exec(e))!==null;){let e=(i[1]??i[2]??``).trim();e&&r.push({label:e,start:i.index,contentStart:i.index+i[0].length})}for(let n=0;n<r.length;n+=1){let i=r[n],a=r[n+1],o=e.slice(i.contentStart,a?.start??e.length).trim();for(let[e,n]of Object.entries(an))cn(i.label,n)&&(t[e]=t[e]?`${t[e]}\n${o}`:o)}return{goal:t.goal?.trim()||e.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>=8)||e.trim(),scope:t.scope?.trim()??``,steps:t.steps?ln(t.steps):[],acceptance:t.acceptance?ln(t.acceptance):[],raw:e.trim()}}function dn(e){let t=e.toLowerCase();return on.some(e=>t.includes(e.toLowerCase()))}function fn(e){return e.some(dn)}function pn(e,t){return{id:e,text:t,required:!0}}function mn(e){return{id:e.id,kind:e.kind,title:e.title,required:!0,status:e.status,acceptanceCriteria:e.acceptanceCriteria,acceptanceEvidence:[],evidenceRefs:[],blockedReason:null,updatedAt:e.updatedAt}}function hn(e){return mn({id:`task-1`,kind:`clarify`,title:nn,status:`doing`,acceptanceCriteria:[pn(`ac-1`,rn)],updatedAt:e})}function gn(e,t,n){let r=e.slice(0,5),i=t.length>0?t.map((e,t)=>pn(`ac-${t+1}`,e)):[pn(`ac-1`,`完成:${r[0]}`)];return r.map((e,t)=>mn({id:`task-${t+1}`,kind:`execution`,title:e,status:t===0?`doing`:`todo`,acceptanceCriteria:t===0?i:[pn(`ac-1`,`完成:${e}`)],updatedAt:n}))}function _n(e){let t=new Date().toISOString(),n=un(e),r=n.goal||n.raw,i=n.scope?[n.scope]:[],a=[];if(n.steps.length>=2)return{interpretation:r,assumptions:i,openQuestions:a,tasks:gn(n.steps,n.acceptance,t)};let o=n.acceptance;if(o.length>0&&fn(o))return{interpretation:r,assumptions:i,openQuestions:a,tasks:gn([n.steps[0]??n.goal],o,t)};if(n.raw.length>=40&&fn(ln(n.raw))){let e=ln(n.raw).filter(dn);return{interpretation:r,assumptions:i,openQuestions:a,tasks:gn([n.goal],e,t)}}return{interpretation:r,assumptions:i,openQuestions:a,tasks:[hn(t)]}}function vn(e,t){return`- [${e?`x`:` `}] ${t.id}: ${t.text}`}function yn(e,t){let n=t??new Set(e.acceptanceEvidence);return[`### ${e.id}: ${e.title}`,``,`Status: ${e.status}`,``,`Acceptance Criteria:`,...e.acceptanceCriteria.map(e=>vn(n.has(e.id),e)),``].join(`
2
2
  `)}function bn(e,t){let n=e.tasks.find(t=>t.id===e.currentTaskId),r=t?.interpretation?.trim()||e.objective,i=t?.assumptions??[],a=t?.openQuestions??[],o=t?.progressLog??[`${new Date(e.updatedAt).toISOString().slice(0,16).replace(`T`,` `)}: 创建目标并生成初始任务。`],s=t?.evidence?.length?t.evidence:e.finalEvidenceRefs.length>0?e.finalEvidenceRefs:[],c=t?.risks??(e.blockedReason?[e.blockedReason]:[]),l=[`# Goal Plan`,``,`## Objective`,``,e.objective,``,`## Interpretation`,``,r,``,`## Assumptions`,``,...i.length>0?i.map(e=>`- ${e}`):[`- 暂无`],``];return t?.taskPlanNotes?.trim()&&l.push(`## Task Plan Notes`,``,t.taskPlanNotes.trim(),``),l.push(`## Current Focus`,``,`- Current task: ${e.currentTaskId??`none`}`,`- Status: ${e.status}`,`- Next step: ${n?.title??`无当前任务`}`,...e.blockedReason?[`- Blocked: ${e.blockedReason}`]:[],``,`## Task List`,``,...e.tasks.flatMap(e=>{let n=new Set,r=t?.criterionEvidence?.[e.id];if(r)for(let t of e.acceptanceCriteria)r.includes(t.id)&&n.add(t.id);else if(e.status===`done`)for(let t of e.acceptanceCriteria)n.add(t.id);return[yn(e,n)]}),`## Progress Log`,``,...o.map(e=>`- ${e}`),``,`## Open Questions`,``,...a.length>0?a.map(e=>`- ${e}`):[`- 暂无`],``,`## Evidence`,``,...s.length>0?s.map(e=>`- ${e}`):[`- 暂无`],``,`## Risks`,``,...c.length>0?c.map(e=>`- ${e}`):[`- 暂无`],``),t?.finalSummary?.trim()&&l.push(`## Final Summary`,``,t.finalSummary.trim(),``),l.join(`
3
3
  `)}const xn=process.platform===`win32`;function Sn(e){return xn?{shell:!0,file:process.env.ComSpec||process.env.COMSPEC||`cmd.exe`,args:[`/d`,`/s`,`/c`,`chcp 65001>nul & ${e}`]}:{file:`bash`,args:[`-lc`,e],shell:void 0}}function Cn(e,t){if(!(e.exitCode!==null||e.signalCode!==null)){if(xn&&typeof e.pid==`number`){let n=[`/pid`,String(e.pid),`/T`];t===`SIGKILL`&&n.push(`/F`);try{Lt(`taskkill`,n,{windowsHide:!0,stdio:`ignore`})}catch{try{e.kill()}catch{}}return}try{if(typeof e.pid==`number`){process.kill(-e.pid,t);return}e.kill(t)}catch{try{e.kill(t)}catch{}}}}const wn=2e5;function Tn(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function En(e,t){let n=e+t;return n.length<=wn?{text:n,truncated:!1}:{text:n.slice(-wn),truncated:!0}}function Dn(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=En(e.output,r);e.output=i.text;let a=En(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function On(e){return{sessionId:e.sessionId,scopeKey:e.scopeKey,command:e.command,cwd:e.cwd,pid:typeof e.child.pid==`number`?e.child.pid:void 0,startedAt:e.startedAt,endedAt:e.endedAt,status:e.status,exitCode:e.exitCode,exitSignal:e.exitSignal,outputTail:Tn(e.output),stdoutTail:Tn(e.stdout),stderrTail:Tn(e.stderr),outputTruncated:e.outputTruncated}}function kn(e,t){return t?e.scopeKey===t:!0}function An(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function jn(e){return e?e.split(/\r?\n/):[]}function Mn(e){let t=jn(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=An(e.limit,n?200:Math.max(1,t.length-r)),a=(n&&t.length>200?t.slice(t.length-200):t.slice(r,r+i)).join(`
4
4
  `);return{sessionId:e.record.sessionId,status:e.record.status,text:a,totalLines:t.length,totalChars:e.record.output.length,truncated:e.record.outputTruncated,exitCode:e.record.exitCode,exitSignal:e.record.exitSignal}}function Nn(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Pn(){let e=new Map,t=new Map,n=n=>{if(e.delete(n.sessionId),t.set(n.sessionId,n),t.size<=100)return;let r=Array.from(t.values()).sort((e,t)=>(e.endedAt??2**53-1)-(t.endedAt??2**53-1));for(;r.length>100;){let e=r.shift();if(!e)break;t.delete(e.sessionId)}},r=n=>e.get(n)??t.get(n)??null,i=(e,t)=>{e.endedAt===void 0&&(t?.(),e.endedAt=Date.now(),n(e),Nn(e))};return{start(t){let{file:n,args:r,shell:a}=Sn(t.command),o=Lt(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,shell:a,detached:!xn}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:Ft(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:o,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:c,resolveDone:s};e.set(l.sessionId,l),o.stdout.on(`data`,e=>Dn(l,`stdout`,e)),o.stderr.on(`data`,e=>Dn(l,`stderr`,e));let u=e=>t=>{Dn(l,`stderr`,Buffer.from(`\n[${e} stream error: ${t.message}]\n`))};o.stdout.on(`error`,u(`stdout`)),o.stderr.on(`error`,u(`stderr`)),o.stdin.on(`error`,u(`stdin`));try{o.stdin.end()}catch{}let d=An(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,Dn(l,`stderr`,Buffer.from(`\n[Timed out after ${d}s]\n`)),Cn(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&Cn(l.child,`SIGKILL`)},1e3))},d*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),Dn(l,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),o.on(`close`,(e,t)=>{i(l,()=>{l.exitCode=e,l.exitSignal=t,l.status===`running`?l.status=e===0?`completed`:`failed`:l.status===`killed`&&e===0&&(l.status=`completed`)})}),On(l)},get(e,t){let n=r(e);return!n||!kn(n,t)?null:On(n)},list(n){return[...e.values(),...t.values()].filter(e=>kn(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>On(e))},async wait(e,t,n){let i=r(e);if(!i||!kn(i,t))return null;if(i.status!==`running`)return On(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!kn(a,t)?null:On(a)},readLog(e){let t=r(e.sessionId);return!t||!kn(t,e.scopeKey)?null:Mn({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!kn(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!kn(n,t))return null;if(n.status!==`running`)return On(n);n.status=`killed`,Cn(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&Cn(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?On(i):null},disposeAll(){for(let t of e.values()){if(t.status!==`running`)continue;t.status=`killed`,Cn(t.child,`SIGTERM`);let e=setTimeout(()=>{(t.status===`running`||t.status===`killed`)&&Cn(t.child,`SIGKILL`)},1e3);typeof e.unref==`function`&&e.unref(),t.killTimer=e}}}}const Fn=1;var In=class extends Error{constructor(e){super(`unsupported_goal_state_version:${e}`),this.name=`UnsupportedGoalStateVersionError`}},Ln=class extends Error{constructor(e){super(e),this.name=`CorruptEvidenceRegistryError`}},Rn=class extends Error{rawContentPreview;constructor(e,t){super(e),this.name=`CorruptGoalWorkflowStateError`,t?.cause!==void 0&&(this.cause=t.cause),this.rawContentPreview=t?.rawContentPreview}};const zn=new Map;function Bn(e,t,n){return`${e}\x00${t}\x00${n?.storeName??``}`}async function Vn(e,t,n,r){let i=Bn(e,t,n),a=zn.get(i)??Promise.resolve(),o,s=new Promise(e=>{o=e});zn.set(i,a.then(()=>s)),await a;try{return await r()}finally{o()}}function Hn(e,t,n){return J.join(ee(e,t,n),`state.json`)}function Un(e,t,n){return J.join(ee(e,t,n),`plan.md`)}function Wn(e,t,n){return J.join(ee(e,t,n),`artifacts`)}async function Gn(e,t){let n=`${e}.${process.pid}.${Date.now()}.${Pt(4).toString(`hex`)}.tmp`;try{await q.writeFile(n,t,`utf-8`),await q.rename(n,e)}finally{await q.unlink(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}}function Kn(e){if(e.version!==1)throw new In(e.version)}function qn(e){let t=e.currentTaskId?e.tasks.find(t=>t.id===e.currentTaskId)??null:null,n=e.tasks.filter(e=>e.required!==!1),r=n.filter(e=>e.status===`done`).length,i=n.filter(e=>e.status!==`done`).length;return{workflowStatus:e.status,currentTaskId:e.currentTaskId,currentTaskTitle:t?.title??null,currentTaskStatus:t?.status??null,blockedReason:e.blockedReason,openRequiredTasks:i,doneRequiredTasks:r,finalEvidenceRefs:[...e.finalEvidenceRefs]}}async function Jn(e,t,n){let r=Hn(e,t,n);try{let e=await q.readFile(r,`utf-8`);try{let t=JSON.parse(e);return Kn(t),t}catch(t){throw t instanceof In?t:new Rn(`corrupt_goal_workflow_state`,{cause:t,rawContentPreview:e.slice(0,200)})}}catch(e){if(e.code===`ENOENT`)return null;throw e instanceof Rn||e instanceof In?e:new Rn(`corrupt_goal_workflow_state`,{cause:e})}}async function Yn(e,t,n){let r=Hn(e,t,n),i;try{i=await q.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{ok:!0,healthy:!0,mode:`absent`};throw e}try{return Kn(JSON.parse(i)),{ok:!0,healthy:!0,mode:`healthy`}}catch(e){if(e instanceof In)throw e}let a=await W(e,t,n);if(!a)throw Error(`repairGoalWorkflowState requires an existing goal record`);let o=(await V(e,t,a,n)).trim();if(!o)throw Error(`repairGoalWorkflowState requires a non-empty objective`);let s=`${r}.corrupt.${new Date().toISOString().replace(/[:.]/g,`-`)}.bak`,c=null;try{await q.writeFile(s,i,`utf-8`),c=s}catch{}return await $n(e,t,{goalId:a.goalId,objective:o},n),await mr(e,t,{type:`goal_workflow_repaired`,goalId:a.goalId,mode:`reinitialized`,backupPath:c},n),{ok:!0,mode:`reinitialized`,goalId:a.goalId,backedUpState:c}}async function Xn(e,t,n){let r=await Jn(e,t,n);return r?qn(r):null}async function Zn(e,t,n){let r=await Jn(e,t,n);return r?{goalState:qn(r),workflowWarning:null}:{goalState:null,workflowWarning:`workflow_not_initialized`}}async function Qn(e,t,n){let r=Hn(e,t,n),i=Un(e,t,n),a=Wn(e,t,n);await Promise.all([q.unlink(r).catch(e=>{if(e.code!==`ENOENT`)throw e}),q.unlink(i).catch(e=>{if(e.code!==`ENOENT`)throw e}),q.rm(a,{recursive:!0,force:!0})])}async function $n(e,t,n,r){let i=n.objective.trim();if(!i)throw Error(`initializeGoalWorkflow requires a non-empty objective`);await Qn(e,t,r);let a=_n(i),o=new Date().toISOString(),s=a.tasks.find(e=>e.status===`doing`)?.id??a.tasks[0]?.id??null,c={version:1,goalId:n.goalId,status:`active`,objective:i,currentTaskId:s,tasks:a.tasks,blockedReason:null,finalEvidenceRefs:[],completedAt:null,updatedAt:o},l=ee(e,t,r);await q.mkdir(l,{recursive:!0}),await Gn(Hn(e,t,r),JSON.stringify(c,null,2));let u=bn(c,{interpretation:a.interpretation,assumptions:a.assumptions,openQuestions:a.openQuestions});return await Gn(Un(e,t,r),u),c}const er=[/(?:api[_-]?key|token|secret|password|authorization)\s*[:=]\s*\S+/gi,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/sk-[A-Za-z0-9]{16,}/g];function tr(e,t,n){return J.join(Wn(e,t,n),`registry.jsonl`)}function nr(e,t,n){return J.join(Wn(e,t,n),`notes`)}function rr(e,t,n){return J.join(ee(e,t,n),`plan-meta.json`)}function ir(e){let t=e,n=!1;for(let e of er)t=t.replace(e,e=>e.length<=8?(n=!0,`[REDACTED]`):`${e.slice(0,4)}[REDACTED]`);return{text:t,redactionIncomplete:n}}function ar(e){return`${e}-${Date.now().toString(36)}-${Pt(3).toString(`hex`)}`}async function or(e,t,n,r){let i=await sr(e,t,r),a=new Set(i.map(e=>e.id));for(let e=0;e<8;e+=1){let e=`${n}:${ar(n)}`;if(!a.has(e))return e}throw Error(`failed_to_generate_unique_evidence_id`)}async function sr(e,t,n){let r=tr(e,t,n);try{let e=await q.readFile(r,`utf-8`),t=[],n=e.split(/\r?\n/).map((e,t)=>({line:e,index:t})).filter(e=>e.line.trim().length>0);for(let[e,r]of n.entries())try{t.push(JSON.parse(r.line))}catch{if(e===n.length-1)continue;throw new Ln(`corrupt evidence registry line ${r.index+1}`)}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function cr(e,t,n,r){let i=tr(e,t,r);await q.mkdir(J.dirname(i),{recursive:!0}),await q.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function lr(e,t,n,r){Kn(n),await Gn(Hn(e,t,r),JSON.stringify(n,null,2))}async function ur(e,t,n){let r=rr(e,t,n);try{let e=await q.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return{};throw e}}async function dr(e,t,n,r){await Gn(rr(e,t,r),JSON.stringify(n,null,2))}async function fr(e,t,n,r){let i=await ur(e,t,r),a={...i,...n,assumptions:n.assumptions??i.assumptions,openQuestions:n.openQuestions??i.openQuestions,progressLog:n.progressLog??i.progressLog,evidence:n.evidence??i.evidence,risks:n.risks??i.risks,criterionEvidence:{...i.criterionEvidence,...n.criterionEvidence}};return await dr(e,t,a,r),a}async function pr(e,t,n,r){try{let i=bn(n,await ur(e,t,r));return await Gn(Un(e,t,r),i),{ok:!0}}catch(e){return{ok:!1,warning:`plan_update_failed`,message:e instanceof Error?e.message:String(e)}}}async function mr(e,t,n,r){let{type:i,...a}=n,o={timestamp:new Date().toISOString(),sessionId:t,goalId:n.goalId??null,action:i,detail:a},s=z(e,t,r);await q.mkdir(J.dirname(s),{recursive:!0}),await q.appendFile(s,`${JSON.stringify(o)}\n`,`utf-8`)}async function hr(e,t,n,r){if(n.kind===`manual`&&!n.source?.trim())return{error:`manual evidence requires source`};if(Buffer.byteLength(n.content,`utf-8`)>65536)return{error:`note_content_too_large`};let i=await or(e,t,n.kind,r),a=i.split(`:`)[1]??ar(n.kind),o=nr(e,t,r);await q.mkdir(o,{recursive:!0});let s=`goal/artifacts/notes/${a}.md`,c=J.join(nr(e,t,r),`${a}.md`),l=ir(n.content);await q.writeFile(c,l.text,`utf-8`);let u={id:i,kind:n.kind,summary:n.summary,source:n.source??`model`,createdAt:new Date().toISOString(),notePath:s,contentBytes:Buffer.byteLength(l.text,`utf-8`),redactionIncomplete:l.redactionIncomplete};try{await cr(e,t,u,r)}catch{return await q.unlink(c).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:i}}function gr(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function _r(e){let t=[`Workflow status: ${e.workflowStatus}`];if(e.currentTaskId&&(t.push(`Current task: ${e.currentTaskId} — ${gr(e.currentTaskTitle??`untitled`)}`,`Current task status: ${e.currentTaskStatus??`unknown`}`),e.currentTaskKind&&t.push(`Current task kind: ${e.currentTaskKind}`)),e.blockedReason&&t.push(`Workflow blocked: ${gr(e.blockedReason)}`),e.taskBlockedReason&&e.taskBlockedReason!==e.blockedReason&&t.push(`Task blocked: ${gr(e.taskBlockedReason)}`),e.acceptanceCriteria.length>0){t.push(``,`Acceptance criteria (current task):`);for(let n of e.acceptanceCriteria){let e=n.required===!1?``:` [required]`;t.push(`- ${n.id}${e}: ${gr(n.text)}`)}}if(e.openQuestions.length>0){t.push(``,`Open questions:`);for(let n of e.openQuestions)t.push(`- ${gr(n)}`)}return t}function vr(e){let t=[`- Treat goal/state.json as the only task workflow machine state; use goal/plan.md for human-readable context.`,`- Work on the current task and acceptance criteria shown in this context.`,`- Do not expose internal workflow files or task mechanics to the user unless they ask for implementation details.`,`- If the overall goal is genuinely achieved, submit goal({ status: "complete", summary }).`,`- If the goal cannot continue without user input or external state, submit goal({ status: "blocked", reason, neededInput }).`,`- Use the current worktree, files, command output, and test results as authoritative evidence.`,`- Do not rely solely on conversation memory to assess completion.`,`- 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 on the current task.`,`- Do not inform the user about this continuation context; treat it as internal steering.`];return(e.currentTaskKind===`clarify`||e.currentTaskTitle===nn)&&t.unshift(`- Current task is "${nn}": explore, clarify, and refine the plan and acceptance criteria.`,`- Do NOT implement deliverables yet; use normal conversation to clarify scope and acceptance before execution work.`),t}function yr(){return[`- 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.`,`- If the overall goal is genuinely achieved, submit goal({ status: "complete", summary }).`,`- If the goal cannot continue without user input or external state, submit goal({ status: "blocked", reason, neededInput }).`,`- 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.`]}const br=`The user just set a thread goal. Acknowledge it implicitly, then work on the current workflow task below.`;function xr(e,t,n){return Sr(e,t,n,{introLine:br})}function Sr(e,t,n,r){let i=gr(t),a=e.tokenBudget===null?`none`:String(e.tokenBudget),o=String(e.tokensUsed),s=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed)),c=n?`The user's thread goal is still active. Continue working on the current workflow task below.`:`The user's thread goal is still active. Continue working toward the objective below.`,l=[`<goal_context>`,``,r?.introLine??c,``,`<objective>`,i,`</objective>`,``,`Token budget: ${a}`,`Tokens used: ${o}`,`Tokens remaining: ${s}`,`Time used: ${e.timeUsedSeconds}s`,``];return n?l.push(`<workflow>`,..._r(n),`</workflow>`,``,`Rules:`,...vr(n)):l.push(`Rules:`,...yr()),l.push(``,`</goal_context>`),l.join(`
5
5
  `)}function Cr(e,t){let n=gr(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 submit 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(`
6
6
  `)}function wr(e,t){let n=gr(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`,``,`Use the goal tool only for terminal complete or blocked status; do not use it for routine progress notes.`,``,`</goal_context>`].join(`
7
- `)}function Tr(e){return{role:`user`,content:e}}function Er(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const Dr=`AIMAX_GOAL_CONTINUATION`;var Or=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function kr(e,t,n){let r=await Jn(e,t,{storeName:n?.storeName});if(!r)return null;let i=await ur(e,t,{storeName:n?.storeName}),a=r.currentTaskId?r.tasks.find(e=>e.id===r.currentTaskId)??null:null;return{workflowStatus:r.status,currentTaskId:r.currentTaskId,currentTaskTitle:a?.title??null,currentTaskKind:a?.kind??null,currentTaskStatus:a?.status??null,blockedReason:r.blockedReason,taskBlockedReason:a?.blockedReason??null,acceptanceCriteria:a?.acceptanceCriteria??[],openQuestions:i.openQuestions??[]}}function Ar(){let e=process.env[Dr];return e===void 0||e===``||e!==`0`}async function jr(e,t,n,r){if(!Ar()||n.continuationCount>=Dt)return!1;let i=await W(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-BaH2Dvmo.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Mr(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Nr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await jr(n,r,a,{storeName:i}))return!1;let u=await W(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 V(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await kr(n,r,{storeName:i}),h=Tr(p?Cr(u,f):Sr(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=Mr(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=Dt){let e=await W(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-CmMXXTIZ.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-BtFriEK5.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 (${Dt}), goal paused`)}}return!0}async function Pr(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function Fr(e,t,n){let r=await Jn(e,t,{storeName:n?.storeName});if(!r||r.status!==`blocked`)return{recovered:!1};let i=r.currentTaskId,a=r.blockedReason,o=new Date().toISOString(),s=r.tasks.map(e=>e.id===i?{...e,status:`doing`,blockedReason:null,updatedAt:o}:e),c={...r,status:`active`,blockedReason:null,tasks:s,updatedAt:o};await lr(e,t,c,{storeName:n?.storeName}),await mr(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await ur(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await fr(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await pr(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function Ir(e,t,n,r){let i=await W(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await kr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=Tr(xr(i,await V(e,t,i,{storeName:r?.storeName}),a)).content;return typeof n==`string`?{prompt:`${o}\n\n${n}`,hadFirstGoalWorkflowSteering:!0}:{prompt:[{role:`user`,content:o,timestamp:Date.now()},...n],hadFirstGoalWorkflowSteering:!0}}async function Lr(e,t,n,r){let i=await W(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=Tr(wr(i,await V(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 Rr(e,t,n){(await W(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await U(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const zr=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function Br(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===nn}function Vr(e){return zr.has(e)}function Hr(e){return e===`exec`||e===`process`?[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before running commands.`].join(` `):[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before executing deliverables directly.`].join(` `)}function Ur(e){let t=!0;return e.hookRegistry.register({pluginId:`goal-clarify-first-turn-gate`,hookName:`before_tool_call`,source:`agents/goal/clarify-first-turn-gate`,priority:100,handler:n=>{if(!(!t||!e.isGateActive())&&Vr(n.toolName))return{block:!0,blockReason:Hr(n.toolName)}}}),()=>{t=!1}}function Wr(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 Gr(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if($r(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}ei(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 Kr(e,t={}){let n=Zr(t.limit,`limit`),r=Qr(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!ei(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:Xr(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function qr(e,t){let n=Qr(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 Jr(e,t=80){let n=Qr(e,`totalEntryCount`),r=Qr(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function Yr(e,t){return e.slice(t.startIndex,t.endIndex)}function Xr(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function Zr(e,t){return e===void 0?1/0:Qr(e,t)}function Qr(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function $r(e){return e.role===`assistant`}function ei(e){return e.role===`tool_result`}const ti=24e3;async function ni(e){return ui({params:e,kind:`current_run`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ri(e){return ui({params:e,kind:`recent_conversation`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ii(e){return ui({params:e,kind:`transcript_range`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ai(e){let t=vi(e),n=await si(e),r=await mi(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:ci(e.dataDir,e.sessionId,e.sessionOptions)}}function oi(e){return{maxEntries:yi(e?.maxEntries??80,`limits.maxEntries`),maxBytes:yi(e?.maxBytes??ti,`limits.maxBytes`)}}async function si(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=di(await fi(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 pi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function ci(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function li(e,t,n){let r=bi(e.startIndex,`startIndex`),i=bi(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 ui(e){let t=vi(e.params),n=li(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=hi(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:ci(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function di(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 fi(e,t,n){let[r,i]=await Promise.all([I(e,t,n),P(e,t,n)]),a=new Map;for(let e of r)Ci(e)&&e.toolResultRef?.sessionId===t&&a.set(wi(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(wi(e),e);return Array.from(a.values())}async function pi(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(J.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=s(e.dataDir,e.sessionId,e.sessionOptions),n=r(e.dataDir,e.sessionId,e.sessionOptions),i=J.resolve(e.dataDir,e.reference.storagePath);if(!Si(J.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Si(J.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([xi(t),xi(n),xi(i)]);if(!Si(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Si(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function mi(e,t){let n=await q.stat(e),r=await q.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:_i(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function hi(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=gi(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 gi(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:_i(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function _i(e){let t=new Rt(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function vi(e){return oi(e.limits)}function yi(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function bi(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function xi(e){try{return await q.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${Ti(e)}`)}}function Si(e,t){let n=J.relative(e,t);return n===``||!n.startsWith(`..`)&&!J.isAbsolute(n)}function Ci(e){return e.role===`tool_result`}function wi(e){return`${e.toolCallId}\n${e.storagePath}`}function Ti(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ei(e){return J.join(e,`.aimax`,`auto-skills`)}function Di(e){return J.join(e,`categories.json`)}function Oi(e){return J.join(e,`.auto_skills_prompt_snapshot.json`)}const ki=/^[a-z0-9][a-z0-9-]*$/,Ai=/^[a-z0-9][a-z0-9-]*$/;function X(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(`\\`)||J.win32.isAbsolute(t)||J.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(!ki.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function ji(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(`.`)||!Ai.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Mi(e,t){return`auto:${X(e)}/${ji(t)}`}function Ni(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=X(n.slice(0,r)),a=ji(n.slice(r+1));return{skillId:Mi(i,a),categoryPath:i,skillName:a}}function Pi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Fi(e,t,n){let r=J.resolve(e),i=J.resolve(r,...X(t).split(`/`),ji(n));return Li(r,i),i}function Ii(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||J.win32.isAbsolute(n)||J.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=J.resolve(e),a=J.resolve(i,...r);return Li(i,a),a}function Li(e,t){let n=J.resolve(e),r=J.resolve(t),i=J.relative(n,r);if(i.startsWith(`..`)||J.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Ri(e){let t=Di(e),n;try{n=await q.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=X(e),r=Bi(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 zi(e){return new Map(e.map(e=>[e.path,e]))}function Bi(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 Vi=32*1024,Hi=new Map;function Ui(e){return new Gi(e)}async function Wi(e){let t=J.resolve(e);for(let e of Array.from(Hi.keys()))e.startsWith(`${t}|`)&&Hi.delete(e);await q.rm(Oi(t),{force:!0}).catch(()=>{})}var Gi=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=J.resolve(e.rootDir??Ei(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return qi(zi((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?X(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>Ji(e.categoryPath,t)).map(Ki)}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:Yi(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})=>({...Ki(e),score:t}))}async autoSkillView(e){let t=Ni(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=Ii(n.skillDir,e.filePath),r=await ia(t,this.maxResourceBytes);return{...Ki(n),status:n.status,content:r,path:sa(J.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:sa(J.relative(n.skillDir,t))}}let r=await ia(n.skillFile,this.maxSkillBytes);return{...Ki(n),status:n.status,content:r,path:sa(J.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 Xi(this.rootDir),i=Hi.get(n);if(!e&&i&&ta(i.manifest,r))return i;let a=e?void 0:await $i(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return Hi.set(n,e),e}let o=await Ri(this.rootDir),s=zi(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return Hi.set(n,c),await ea(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 ua({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:Vi})}async loadEntry(e){try{let t=J.dirname(e),n=ji(J.basename(t)),r=sa(J.relative(this.rootDir,t)),i=X(J.posix.dirname(r)),a=Mi(i,n),o=J.join(t,`metadata.json`),s=await na(o);if(s?.skillId&&Ni(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&X(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=Pi(s?.status);return{skillId:a,name:n,description:aa(await ra(e,Vi)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:oa(s?.tags),relatedSkills:oa(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}: ${ca(t)}\n`);return}}};function Ki(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function qi(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function Ji(e,t){return t?e===t:!0}function Yi(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 Xi(e){let t;try{t=await q.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await Qi(J.join(e,`categories.json`),`categories`,n),await Zi(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function Zi(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=J.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await Qi(t,`skill`,n),await Qi(J.join(e,`metadata.json`),`metadata`,n),await Qi(J.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await q.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await Zi(t,i,n)}}async function Qi(e,t,n){try{let r=await q.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 $i(e,t,n){let r;try{r=await q.readFile(Oi(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)||!ta(e.manifest,n)?void 0:e}catch{return}}async function ea(e,t){if(!await la(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await q.writeFile(Oi(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function ta(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 na(e){try{let t=await q.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 ra(e,t){let n=await q.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 ia(e,t){if((await q.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return q.readFile(e,`utf-8`)}function aa(e){let t=zt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
7
+ `)}function Tr(e){return{role:`user`,content:e}}function Er(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const Dr=`AIMAX_GOAL_CONTINUATION`;var Or=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function kr(e,t,n){let r=await Jn(e,t,{storeName:n?.storeName});if(!r)return null;let i=await ur(e,t,{storeName:n?.storeName}),a=r.currentTaskId?r.tasks.find(e=>e.id===r.currentTaskId)??null:null;return{workflowStatus:r.status,currentTaskId:r.currentTaskId,currentTaskTitle:a?.title??null,currentTaskKind:a?.kind??null,currentTaskStatus:a?.status??null,blockedReason:r.blockedReason,taskBlockedReason:a?.blockedReason??null,acceptanceCriteria:a?.acceptanceCriteria??[],openQuestions:i.openQuestions??[]}}function Ar(){let e=process.env[Dr];return e===void 0||e===``||e!==`0`}async function jr(e,t,n,r){if(!Ar()||n.continuationCount>=Dt)return!1;let i=await W(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-BwYOp-2K.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Mr(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Nr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await jr(n,r,a,{storeName:i}))return!1;let u=await W(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 V(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await kr(n,r,{storeName:i}),h=Tr(p?Cr(u,f):Sr(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=Mr(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=Dt){let e=await W(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-M3_Nx3ky.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-CocRykqc.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 (${Dt}), goal paused`)}}return!0}async function Pr(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function Fr(e,t,n){let r=await Jn(e,t,{storeName:n?.storeName});if(!r||r.status!==`blocked`)return{recovered:!1};let i=r.currentTaskId,a=r.blockedReason,o=new Date().toISOString(),s=r.tasks.map(e=>e.id===i?{...e,status:`doing`,blockedReason:null,updatedAt:o}:e),c={...r,status:`active`,blockedReason:null,tasks:s,updatedAt:o};await lr(e,t,c,{storeName:n?.storeName}),await mr(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await ur(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await fr(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await pr(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function Ir(e,t,n,r){let i=await W(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await kr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=Tr(xr(i,await V(e,t,i,{storeName:r?.storeName}),a)).content;return typeof n==`string`?{prompt:`${o}\n\n${n}`,hadFirstGoalWorkflowSteering:!0}:{prompt:[{role:`user`,content:o,timestamp:Date.now()},...n],hadFirstGoalWorkflowSteering:!0}}async function Lr(e,t,n,r){let i=await W(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=Tr(wr(i,await V(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 Rr(e,t,n){(await W(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await U(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const zr=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function Br(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===nn}function Vr(e){return zr.has(e)}function Hr(e){return e===`exec`||e===`process`?[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before running commands.`].join(` `):[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before executing deliverables directly.`].join(` `)}function Ur(e){let t=!0;return e.hookRegistry.register({pluginId:`goal-clarify-first-turn-gate`,hookName:`before_tool_call`,source:`agents/goal/clarify-first-turn-gate`,priority:100,handler:n=>{if(!(!t||!e.isGateActive())&&Vr(n.toolName))return{block:!0,blockReason:Hr(n.toolName)}}}),()=>{t=!1}}function Wr(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 Gr(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if($r(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}ei(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 Kr(e,t={}){let n=Zr(t.limit,`limit`),r=Qr(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!ei(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:Xr(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function qr(e,t){let n=Qr(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 Jr(e,t=80){let n=Qr(e,`totalEntryCount`),r=Qr(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function Yr(e,t){return e.slice(t.startIndex,t.endIndex)}function Xr(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function Zr(e,t){return e===void 0?1/0:Qr(e,t)}function Qr(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function $r(e){return e.role===`assistant`}function ei(e){return e.role===`tool_result`}const ti=24e3;async function ni(e){return ui({params:e,kind:`current_run`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ri(e){return ui({params:e,kind:`recent_conversation`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ii(e){return ui({params:e,kind:`transcript_range`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ai(e){let t=vi(e),n=await si(e),r=await mi(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:ci(e.dataDir,e.sessionId,e.sessionOptions)}}function oi(e){return{maxEntries:yi(e?.maxEntries??80,`limits.maxEntries`),maxBytes:yi(e?.maxBytes??ti,`limits.maxBytes`)}}async function si(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=di(await fi(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 pi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function ci(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function li(e,t,n){let r=bi(e.startIndex,`startIndex`),i=bi(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 ui(e){let t=vi(e.params),n=li(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=hi(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:ci(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function di(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 fi(e,t,n){let[r,i]=await Promise.all([I(e,t,n),P(e,t,n)]),a=new Map;for(let e of r)Ci(e)&&e.toolResultRef?.sessionId===t&&a.set(wi(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(wi(e),e);return Array.from(a.values())}async function pi(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(J.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=s(e.dataDir,e.sessionId,e.sessionOptions),n=r(e.dataDir,e.sessionId,e.sessionOptions),i=J.resolve(e.dataDir,e.reference.storagePath);if(!Si(J.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Si(J.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([xi(t),xi(n),xi(i)]);if(!Si(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Si(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function mi(e,t){let n=await q.stat(e),r=await q.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:_i(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function hi(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=gi(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 gi(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:_i(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function _i(e){let t=new Rt(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function vi(e){return oi(e.limits)}function yi(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function bi(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function xi(e){try{return await q.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${Ti(e)}`)}}function Si(e,t){let n=J.relative(e,t);return n===``||!n.startsWith(`..`)&&!J.isAbsolute(n)}function Ci(e){return e.role===`tool_result`}function wi(e){return`${e.toolCallId}\n${e.storagePath}`}function Ti(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ei(e){return J.join(e,`.aimax`,`auto-skills`)}function Di(e){return J.join(e,`categories.json`)}function Oi(e){return J.join(e,`.auto_skills_prompt_snapshot.json`)}const ki=/^[a-z0-9][a-z0-9-]*$/,Ai=/^[a-z0-9][a-z0-9-]*$/;function X(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(`\\`)||J.win32.isAbsolute(t)||J.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(!ki.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function ji(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(`.`)||!Ai.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Mi(e,t){return`auto:${X(e)}/${ji(t)}`}function Ni(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=X(n.slice(0,r)),a=ji(n.slice(r+1));return{skillId:Mi(i,a),categoryPath:i,skillName:a}}function Pi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Fi(e,t,n){let r=J.resolve(e),i=J.resolve(r,...X(t).split(`/`),ji(n));return Li(r,i),i}function Ii(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||J.win32.isAbsolute(n)||J.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=J.resolve(e),a=J.resolve(i,...r);return Li(i,a),a}function Li(e,t){let n=J.resolve(e),r=J.resolve(t),i=J.relative(n,r);if(i.startsWith(`..`)||J.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Ri(e){let t=Di(e),n;try{n=await q.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=X(e),r=Bi(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 zi(e){return new Map(e.map(e=>[e.path,e]))}function Bi(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 Vi=32*1024,Hi=new Map;function Ui(e){return new Gi(e)}async function Wi(e){let t=J.resolve(e);for(let e of Array.from(Hi.keys()))e.startsWith(`${t}|`)&&Hi.delete(e);await q.rm(Oi(t),{force:!0}).catch(()=>{})}var Gi=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=J.resolve(e.rootDir??Ei(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return qi(zi((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?X(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>Ji(e.categoryPath,t)).map(Ki)}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:Yi(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})=>({...Ki(e),score:t}))}async autoSkillView(e){let t=Ni(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=Ii(n.skillDir,e.filePath),r=await ia(t,this.maxResourceBytes);return{...Ki(n),status:n.status,content:r,path:sa(J.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:sa(J.relative(n.skillDir,t))}}let r=await ia(n.skillFile,this.maxSkillBytes);return{...Ki(n),status:n.status,content:r,path:sa(J.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 Xi(this.rootDir),i=Hi.get(n);if(!e&&i&&ta(i.manifest,r))return i;let a=e?void 0:await $i(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return Hi.set(n,e),e}let o=await Ri(this.rootDir),s=zi(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return Hi.set(n,c),await ea(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 ua({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:Vi})}async loadEntry(e){try{let t=J.dirname(e),n=ji(J.basename(t)),r=sa(J.relative(this.rootDir,t)),i=X(J.posix.dirname(r)),a=Mi(i,n),o=J.join(t,`metadata.json`),s=await na(o);if(s?.skillId&&Ni(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&X(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=Pi(s?.status);return{skillId:a,name:n,description:aa(await ra(e,Vi)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:oa(s?.tags),relatedSkills:oa(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}: ${ca(t)}\n`);return}}};function Ki(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function qi(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function Ji(e,t){return t?e===t:!0}function Yi(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 Xi(e){let t;try{t=await q.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await Qi(J.join(e,`categories.json`),`categories`,n),await Zi(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function Zi(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=J.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await Qi(t,`skill`,n),await Qi(J.join(e,`metadata.json`),`metadata`,n),await Qi(J.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await q.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await Zi(t,i,n)}}async function Qi(e,t,n){try{let r=await q.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 $i(e,t,n){let r;try{r=await q.readFile(Oi(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)||!ta(e.manifest,n)?void 0:e}catch{return}}async function ea(e,t){if(!await la(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await q.writeFile(Oi(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function ta(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 na(e){try{let t=await q.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 ra(e,t){let n=await q.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 ia(e,t){if((await q.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return q.readFile(e,`utf-8`)}function aa(e){let t=zt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
8
8
  `)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function oa(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function sa(e){return e.split(J.sep).join(`/`)}function ca(e){return e instanceof Error?e.message:String(e)}async function la(e){try{return await q.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function ua(e){return Nt(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function da(e,t,n,r){return se(ce(e.apiFormat)).createModel(e,t,n,r)}const fa=`/aimax/agents`,pa=/^[a-z]+(?:-[a-z]+)*$/;function ma(e){let t=[{dir:e.systemAgentsDir??fa,source:`system`},{dir:J.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:J.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function ha(e){let t=new Map;for(let n of ma(e)){let e=await ya(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function ga(e={}){let t=e.allAgents??e.availableAgents??[],n=Ca(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>xa(n,e),findAny:e=>xa(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function _a(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 va(e){return _a(e.agentPolicy)?e.agentPolicy:ga({allAgents:await ha(e)})}async function ya(e,t){let n;try{n=await q.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=J.join(e,i.name),a=ba(await q.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function ba(e,t){let n=zt(e),r=Oa(n.data.name)?.trim(),i=Oa(n.data.description)?.trim();if(!r||!pa.test(r)||!i)return;let a=Oa(n.data.model)?.trim(),o=Oa(n.data.initPrompt)?.trim()??Oa(n.data.initialPrompt)?.trim(),s=ka(n.data.maxTurns),c=Aa(n.data.tools),l=Aa(n.data.disallowedTools),u=Aa(n.data.skills),d=ja(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 xa(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Sa(e)===`public`))}function Sa(e){return e.visibility??`public`}function Ca(e){return e.filter(e=>Sa(e)===`public`)}function wa(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Ta(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Ma)):void 0,r=new Set((t.disallowedTools??[]).map(Ma));return e.filter(e=>{let t=typeof e.name==`string`?Ma(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Ea(e){let t=Ca(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(`
9
9
  `),``].join(`
10
10
  `)}function Da(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Oa(e){return typeof e==`string`?e:void 0}function ka(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Aa(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 ja(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function Ma(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}var Na=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}:{}};try{await this.params.onProgress?.(n)}catch(n){K.warn(`progress handler failed; event dropped`,{sessionId:e,eventType:t.type,error:n instanceof Error?n.message:String(n)})}}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}};const Pa=`<aimax_artifacts>`,Fa=`</aimax_artifacts>`;function Ia(e,t={}){let n=[];if(!e.includes(Pa))return{cleanedText:e,artifacts:[],warnings:n};let r=e,i,a=[];for(;;){let e=r.indexOf(Pa);if(e===-1)break;let o=r.indexOf(Fa,e+17);if(o===-1){n.push(`Artifacts block is missing the closing tag; stripping the malformed block`),r=r.slice(0,e).trimEnd();break}let s=r.slice(e+17,o).trim();s&&(i??=(t.now??(()=>new Date))().toISOString(),a.push(...La(s,{warnings:n,timestamp:i,workspaceDir:t.workspaceDir}))),r=[r.slice(0,e).trimEnd(),r.slice(o+18).trimStart()].filter(e=>e.length>0).join(`
@@ -186,7 +186,7 @@ Preview:
186
186
 
187
187
  ---
188
188
 
189
- `)}`}async function Zv(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i,runtimeBridge:a}=e,o=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},s=t.plugins?Date.now():void 0,c=t.plugins?Ce({...t.plugins,config:t.plugins.config,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist,env:t.env}}):void 0,l=s===void 0?void 0:Math.max(0,Date.now()-s);if(!c)return o({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`}),{hookRegistry:new le,pluginSkillDirs:[],pluginTools:[]};o({level:c.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:c.registry.plugins.length,enabledPluginCount:c.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:c.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:c.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:c.diagnostics.length,durationMs:l}});for(let e of c.registry.plugins)o({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,durationMs:e.durationMs,errorMessage:e.error}});for(let e of c.diagnostics)o({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}});let u=ke(c.normalizedConfig),d;if(u.length>0){let e=await Oe(c.normalizedConfig);if(e.length>0){d=new et(e);let s=n.session?.getSessionDir?.(),l=t.createPiExtensionDialogBridge?.(r),u={};for(let[e,t]of Object.entries(c.normalizedConfig.entries??{}))t?.config&&typeof t.config==`object`&&(u[e]=t.config);let f=new Map;for(let t of e){let e=`pi:${t.name}`;u[e]&&f.set(e,u[e])}await d.activate({hookRegistry:c.registry.hooks,toolRegistry:c.registry.tools,hookContext:n,eventDispatcher:i,sessionId:r,sessionDir:s,runtimeBridge:a,dialogBridge:l,piExtensionConfigs:f}),o({level:`info`,scope:`plugin`,phase:`pi_extensions_activated`,message:`pi extensions activated`,details:{extensionCount:e.length,extensionNames:e.map(e=>e.name),commandCount:d.getRegisteredCommands().size}})}}return{hookRegistry:c.registry.hooks,pluginSkillDirs:c.registry.skills,pluginTools:[...c.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...c.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??c.normalizedConfig.slots?.memory,extensionHost:d}}var Qv=class{agent=null;messageQueue=[];compactRequest=null;bindAgent(e){this.agent=e}dispose(){this.agent=null,this.messageQueue=[],this.compactRequest=null}sendUserMessage(e,t){this.messageQueue.push({content:e,deliverAs:t?.deliverAs,resolve:()=>{}})}isIdle(){if(!this.agent)return!0;let e=this.agent.state;return!e.isStreaming&&(e.pendingToolCalls?.size??0)===0}requestCompact(e){this.compactRequest=e??{}}drainMessages(){let e=this.messageQueue.map(e=>e.content);return this.messageQueue=[],e}drainCompactRequest(){let e=this.compactRequest;return this.compactRequest=null,e}hasPendingMessages(){return this.messageQueue.length>0}hasPendingCompact(){return this.compactRequest!==null}};async function $v(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=Kp(t),o=n,s=!o,c=$(t);o?(await w(t.dataDir,o,c)||(s=!0),await v(t.dataDir,o,c)):o=await T(t.dataDir,t.channel,{...c});let l={sessionId:o,workspaceDir:a,channel:t.channel,session:{getSessionId:()=>o,getSessionDir:()=>r(t.dataDir,o,c),getEntries:()=>I(t.dataDir,o,c)}},u=new Qv,d=await Zv({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await qp({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:d.memoryPluginId,eventDispatcher:i,hookRegistry:f});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:f,pluginContext:d,runContext:p,runtimeBridge:u,start:e=>H_({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function ey(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function ty(e){if(!(e instanceof Error))return{errorValue:ey(e)};let t={errorName:e.name,errorMessage:e.message};e.stack&&(t.stack=e.stack);let n=e;for(let e of[`code`,`statusCode`,`statusText`,`providerMessage`,`retryable`,`cause`])n[e]!==void 0&&(t[e]=ey(n[e]));return t}async function ny(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...ty(e.error)}})}function ry(e,t,n){return J.join(r(e,t,n),`pending-ui-tool.json`)}async function iy(e,t,n,i){let a=r(e,t,i);await q.mkdir(a,{recursive:!0}),await R(ry(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function ay(e,t,n){let r=await o(ry(e,t,n));return r===null?null:JSON.parse(r)}async function oy(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await iy(e,t,a,r),a}async function sy(e,t,n,r,i){let a=await ay(e,t,i);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o={...a,status:`resolved`,result:r,updatedAt:new Date().toISOString()};return await iy(e,t,o,i),o}async function cy(e,t,n){try{await q.unlink(ry(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function ly(e,t,n,r){let i=await W(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function uy(e,t,n,r,i,a){let o=await W(e,t,{storeName:a?.storeName});await ly(e,t,n,a);let s=await tn(e,t,n,r,a);return s.goal&&await Bv(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function dy(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!At(t))}async function fy(e){let t=e.params.hitlResume,n=t?.toolContext;if(!t||!n)throw Error(`before-tool HITL resume requires toolContext`);if(!(t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1))){let t=`HITL approval denied; tool execution skipped.`;return await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:t,isError:!0,timestamp:new Date().toISOString()}),{text:t,error:t}}let r=(Array.isArray(e.agent.state.tools)?e.agent.state.tools:[]).find(e=>e&&typeof e==`object`&&e.name===n.toolName&&typeof e.execute==`function`);if(!r)throw Error(`Cannot resume HITL tool call: tool not found: ${n.toolName}`);await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_start`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs});let i,a=!1;try{let t=yo();if(i=await bo(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(_o(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=py(i),s=i&&typeof i==`object`?i.details:void 0,c=s&&typeof s==`object`?s.toolResultRef:void 0;return await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_end`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs,output:o,isError:a}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:o,isError:a,...c?{toolResultRef:c}:{},timestamp:new Date().toISOString()}),{text:o,error:a?o:void 0}}function py(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}const my=2e4,hy=15e4,gy=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function _y(e){return J.join(e,`.aimax`)}async function vy(e){let t=_y(e),n=[];for(let e of gy){let r=J.join(t,e);try{let t=await q.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await q.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 yy(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(`
189
+ `)}`}async function Zv(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i,runtimeBridge:a}=e,o=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},s=t.plugins?Date.now():void 0,c=t.plugins?Ce({...t.plugins,config:t.plugins.config,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist,env:t.env}}):void 0,l=s===void 0?void 0:Math.max(0,Date.now()-s);if(!c)return o({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`}),{hookRegistry:new le,pluginSkillDirs:[],pluginTools:[]};o({level:c.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:c.registry.plugins.length,enabledPluginCount:c.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:c.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:c.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:c.diagnostics.length,durationMs:l}});for(let e of c.registry.plugins)o({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,durationMs:e.durationMs,errorMessage:e.error}});for(let e of c.diagnostics)o({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}});let u=ke(c.normalizedConfig),d;if(u.length>0){let e=await Oe(c.normalizedConfig);if(e.length>0){d=new et(e);let s=n.session?.getSessionDir?.(),l=t.createPiExtensionDialogBridge?.(r),u={};for(let[e,t]of Object.entries(c.normalizedConfig.entries??{}))t?.config&&typeof t.config==`object`&&(u[e]=t.config);let f=new Map;for(let t of e){let e=`pi:${t.name}`;u[e]&&f.set(e,u[e])}await d.activate({hookRegistry:c.registry.hooks,toolRegistry:c.registry.tools,hookContext:n,eventDispatcher:i,sessionId:r,sessionDir:s,runtimeBridge:a,dialogBridge:l,piExtensionConfigs:f}),o({level:`info`,scope:`plugin`,phase:`pi_extensions_activated`,message:`pi extensions activated`,details:{extensionCount:e.length,extensionNames:e.map(e=>e.name),commandCount:d.getRegisteredCommands().size}})}}return{hookRegistry:c.registry.hooks,pluginSkillDirs:c.registry.skills,pluginTools:[...c.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...c.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??c.normalizedConfig.slots?.memory,extensionHost:d}}var Qv=class{agent=null;messageQueue=[];compactRequest=null;bindAgent(e){this.agent=e}dispose(){this.agent=null,this.messageQueue=[],this.compactRequest=null}sendUserMessage(e,t){this.messageQueue.push({content:e,deliverAs:t?.deliverAs,resolve:()=>{}})}isIdle(){if(!this.agent)return!0;let e=this.agent.state;return!e.isStreaming&&(e.pendingToolCalls?.size??0)===0}requestCompact(e){this.compactRequest=e??{}}drainMessages(){let e=this.messageQueue.map(e=>e.content);return this.messageQueue=[],e}drainCompactRequest(){let e=this.compactRequest;return this.compactRequest=null,e}hasPendingMessages(){return this.messageQueue.length>0}hasPendingCompact(){return this.compactRequest!==null}};async function $v(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=Kp(t),o=n,s=!o,c=$(t);o?(await w(t.dataDir,o,c)||(s=!0),await v(t.dataDir,o,c)):o=await T(t.dataDir,t.channel,{...c});let l={sessionId:o,messageId:t.messageId,workspaceDir:a,channel:t.channel,session:{getSessionId:()=>o,getSessionDir:()=>r(t.dataDir,o,c),getEntries:()=>I(t.dataDir,o,c)}},u=new Qv,d=await Zv({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await qp({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:d.memoryPluginId,eventDispatcher:i,hookRegistry:f});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:f,pluginContext:d,runContext:p,runtimeBridge:u,start:e=>H_({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function ey(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function ty(e){if(!(e instanceof Error))return{errorValue:ey(e)};let t={errorName:e.name,errorMessage:e.message};e.stack&&(t.stack=e.stack);let n=e;for(let e of[`code`,`statusCode`,`statusText`,`providerMessage`,`retryable`,`cause`])n[e]!==void 0&&(t[e]=ey(n[e]));return t}async function ny(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...ty(e.error)}})}function ry(e,t,n){return J.join(r(e,t,n),`pending-ui-tool.json`)}async function iy(e,t,n,i){let a=r(e,t,i);await q.mkdir(a,{recursive:!0}),await R(ry(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function ay(e,t,n){let r=await o(ry(e,t,n));return r===null?null:JSON.parse(r)}async function oy(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await iy(e,t,a,r),a}async function sy(e,t,n,r,i){let a=await ay(e,t,i);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o={...a,status:`resolved`,result:r,updatedAt:new Date().toISOString()};return await iy(e,t,o,i),o}async function cy(e,t,n){try{await q.unlink(ry(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function ly(e,t,n,r){let i=await W(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function uy(e,t,n,r,i,a){let o=await W(e,t,{storeName:a?.storeName});await ly(e,t,n,a);let s=await tn(e,t,n,r,a);return s.goal&&await Bv(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function dy(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!At(t))}async function fy(e){let t=e.params.hitlResume,n=t?.toolContext;if(!t||!n)throw Error(`before-tool HITL resume requires toolContext`);if(!(t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1))){let t=`HITL approval denied; tool execution skipped.`;return await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:t,isError:!0,timestamp:new Date().toISOString()}),{text:t,error:t}}let r=(Array.isArray(e.agent.state.tools)?e.agent.state.tools:[]).find(e=>e&&typeof e==`object`&&e.name===n.toolName&&typeof e.execute==`function`);if(!r)throw Error(`Cannot resume HITL tool call: tool not found: ${n.toolName}`);await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_start`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs});let i,a=!1;try{let t=yo();if(i=await bo(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(_o(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=py(i),s=i&&typeof i==`object`?i.details:void 0,c=s&&typeof s==`object`?s.toolResultRef:void 0;return await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_end`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs,output:o,isError:a}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:o,isError:a,...c?{toolResultRef:c}:{},timestamp:new Date().toISOString()}),{text:o,error:a?o:void 0}}function py(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}const my=2e4,hy=15e4,gy=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function _y(e){return J.join(e,`.aimax`)}async function vy(e){let t=_y(e),n=[];for(let e of gy){let r=J.join(t,e);try{let t=await q.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await q.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 yy(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(`
190
190
  `),s].join(`
191
191
  `),truncated:!0,originalLength:r.length}}function by(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function xy(e,t){let n=t?.maxChars??my,r=Math.max(1,t?.totalMaxChars??Math.max(n,hy)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=by(`[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}=yy(a.content??``,a.name,e),l=by(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 Sy=`You are a personal assistant running inside AiMax.`;async function Cy(e){try{return{presetSystemPrompt:zt(await q.readFile(e,`utf-8`)).content.trim()||Sy}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:Sy};throw e}}async function wy(){return Cy(`/aimax_pvc/system_prompt.md`)}async function Ty(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await vy(t.dataDir),o=[],s=xy(a,{warn:e=>o.push(e)}),c=await wy();await i.dispatchDiagnostic(n,{level:o.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length}}),K.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await Mf(t.dataDir,r.pluginSkillDirs,l),d=await va({dataDir:t.dataDir,projectDir:t.projectDir,systemAgentsDir:t.systemAgentsDir,agentPolicy:t.agentPolicy}),f=d.stats(),p=t.agentPolicy?.activeAgent??d.findPublic(t.agentPolicy?.requestedAgentName);if(t.agentPolicy?.requestedAgentName&&!p)throw Error(`Unknown custom agent: ${t.agentPolicy.requestedAgentName}`);let m={...d,...p?{activeAgent:p}:{},...t.agentPolicy?.requestedAgentName?{requestedAgentName:t.agentPolicy.requestedAgentName}:{}},h={...t,agentPolicy:m};return await i.dispatchDiagnostic(n,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length,skills:u.map(e=>({name:e.name,description:e.description,location:e.location}))}}),K.info(`skills loaded`,{sessionId:n,skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length}),await i.dispatchDiagnostic(n,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,agents:d.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),K.info(`custom agents loaded`,{sessionId:n,agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,requestedAgentName:m.requestedAgentName}),{contextFiles:s,bootstrapWarnings:o,skills:u,autoSkillCategories:await Ey({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function Ey(e){if(!e.enabled)return[];try{let t=await new Gi({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}var Dy=class{#e=0;#t=0;add(e,t){this.#e+=e,this.#t+=t}snapshot(){return{input:this.#e,output:this.#t,total:this.#e+this.#t}}};const Oy={Inferred:1,Child:2,Own:3};var ky=class{records=[];indices=new Map;urlWhitelist;constructor(e={}){let t=jy(e.urlWhitelist);this.urlWhitelist=t.length>0?new Set(t):void 0}addOwn(e){this.add(e,Oy.Own)}addInferred(e){this.add(e,Oy.Inferred)}addChild(e){e&&e.length>0&&this.add(e,Oy.Child)}dump(){return this.records.map(e=>e.record)}add(e,t){for(let n of e){if(!this.shouldCollect(n))continue;let e=Ay(n),r=this.indices.get(e);if(r!==void 0){let e=this.records[r];e&&t>e.priority&&(this.records[r]={record:n,priority:t});continue}this.indices.set(e,this.records.length),this.records.push({record:n,priority:t})}}shouldCollect(e){if(e.kind!==`url`||!this.urlWhitelist)return!0;let t=My(e.url);return t?this.urlWhitelist.has(t):!1}};function Ay(e){return e.kind===`file`?`file:${e.file}`:`url:${e.url}`}function jy(e){return e?e.map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function My(e){try{return new URL(e).hostname.trim().toLowerCase()||null}catch{return null}}const Ny=`crons`;function Py(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:ie(e.message)}}async function Fy(e){let t,n=0,r=0,i;if(e.runtimeBridge.hasPendingMessages()){let a=e.runtimeBridge.drainMessages();for(let o of a){let a=await Uh({agent:e.agent,message:o,continueFromHistory:!1,sessionId:e.sessionId,channel:e.channel,modelId:e.resolvedModelId,historyMessages:e.runtime.historyMessages,eventDispatcher:e.eventDispatcher,hooks:e.hookRegistry,hookCtx:e.hookContext,abortSignal:e.abortSignal,retry:e.retry,onTurnRecordProduced:async(t,n)=>{t&&await e.appendEntry(t);for(let t of n)await e.appendEntry(t)}});n+=a.inputTokens,r+=a.outputTokens,a.text&&(t=a.text),a.error&&(i=a.error);let s=await Yv({agent:e.agent,registry:e.registry,sessionId:e.sessionId,resolvedModelId:e.resolvedModelId,eventDispatcher:e.eventDispatcher,hookRegistry:e.hookRegistry,hookContext:e.hookContext,abortSignal:e.abortSignal,appendEntry:e.appendEntry});n+=s.inputTokens,r+=s.outputTokens,s.text&&(t=s.text),s.error&&!i&&(i=s.error)}}let a=e.runtimeBridge.drainCompactRequest();if(a)try{let t=await jv({entries:e.runParams.channel===`CRON`?[]:await I(e.runParams.dataDir,e.sessionId,$(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{apiFormat:e.runParams.llm.apiFormat,baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:a.customInstructions,signal:e.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});t.status===`compacted`&&await e.appendEntry(t.entry),a.onComplete?.(t)}catch(e){a.onError?.(e instanceof Error?e:Error(String(e)))}return{lastResponseText:t,inputTokens:n,outputTokens:r,error:i}}async function Iy(e,t){P_();let n=Date.now(),i=new Na(e),a=new ky({urlWhitelist:e.artifactsUrlWhitelist}),o=Vv(e);K.info(`agent invocation prepared`,{requestedSessionId:o.requestedSessionId,previousSessionId:o.previousSessionId,inputMode:o.inputMode,hasSlashCommand:!!o.slashCommandSource,resetAction:o.resetCommand?.action,resetShortCircuit:o.resetShortCircuit,transcriptLength:o.transcriptMessage.length,messageForRunLength:o.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let s=o.transcriptMessage,c=!1,l=o.previousSessionId,u=await $v({runParams:e,requestedSessionId:o.requestedSessionId,eventDispatcher:i}),d=u.sessionId;de(e.dataDir,{messageId:e.messageId,sessionId:d,sessionStoreName:e.sessionStoreName,sessionDir:r(e.dataDir,d,$(e))});let f=u.isNewSession,m=u.workspaceDir,h=u.hookContext,g=u.hookRegistry,_=u.pluginContext,v=u.runContext,y=u.runtimeBridge,b=0,x=!1,S=()=>{x||(x=!0,y.dispose())},C=(await I(e.dataDir,d,$(e))).length;if(K.info(`agent run started`,{sessionId:d,requestedSessionId:o.requestedSessionId,previousSessionId:l,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:f,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:f,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),K.info(f?`session created`:`session resumed`,{sessionId:d,requestedSessionId:o.requestedSessionId,previousSessionId:l,workspaceDir:m}),await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:f?`session_created`:`session_resumed`,message:f?`session created`:`session resumed`,details:{requestedSessionId:o.requestedSessionId,previousSessionId:l,workspaceDir:m}}),f&&await p(e.dataDir,Yp({sessionId:d,title:V_(s),channel:e.channel}),$(e)),e.pendingGoal){let t=await G(e.dataDir,d,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`});await $n(e.dataDir,d,{goalId:t.goalId,objective:e.pendingGoal.objective},{storeName:e.sessionStoreName})}o.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(c=await v.persistInitialUserEntry(s));let w=new AbortController;e.abortSignal?.aborted?w.abort():e.abortSignal?.addEventListener(`abort`,()=>w.abort()),h.signal=w.signal,await u.start({resetCommand:o.resetCommand,previousSessionId:l,resetMessage:o.slashCommandSource,startMessage:typeof o.promptInput==`string`?o.promptInput:s});let T=await Ty({runParams:e,sessionId:d,pluginContext:_,eventDispatcher:i}),E=e=>v.appendTranscriptEntry(e),D=await Uv({invocation:o,skills:T.skills,sessionId:d,isNewSession:f,initialUserEntryPersisted:c,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,extensionHost:_.extensionHost});if(D.kind===`completed`)return K.info(`agent run short-circuited`,{sessionId:d,durationMs:Date.now()-n,hasError:!!D.result.error,paused:!!D.result.paused,uiToolPending:!!D.result.uiToolPending,textLength:D.result.text.length}),S(),D.result;let O=D.effectivePrompt;s=D.transcriptMessage;let k=typeof O==`string`?O:s;await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length}}),K.info(`invocation resolved`,{sessionId:d,promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length});let A=await Dh({session:{runParams:T.runParamsWithAgentPolicy,sessionId:d,hookRegistry:g,hookContext:h,runContext:v,eventDispatcher:i},runtimeInputs:{contextFiles:T.contextFiles,bootstrapWarnings:T.bootstrapWarnings,skills:T.skills,autoSkillCategories:T.autoSkillCategories,effectivePromptText:k,pluginTools:_.pluginTools,pluginSkillDirs:_.pluginSkillDirs,skillsLoadPaths:T.skillsLoadPaths,presetSystemPrompt:T.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>Iy(e,new Ap),createModel:da,abortSignal:w.signal}}),j=A.agent,M=A.resolvedModelId;y.bindAgent(j),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length}}),K.info(`agent runtime created`,{sessionId:d,modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length});let N=Hy(e.timeoutMs),P=!1,F=N===void 0?void 0:setTimeout(()=>{P=!0,w.abort(),j.abort(),i.dispatchDiagnostic(d,{level:`warn`,scope:`runner`,phase:`run_timeout`,message:`agent run timed out`,details:{timeoutMs:N}}),K.warn(`agent run timed out`,{sessionId:d,timeoutMs:N})},N);w.signal.addEventListener(`abort`,()=>j.abort());let L=new Dy,R=``,z,B=!1,V=new en;await ly(e.dataDir,d,V,{storeName:e.sessionStoreName}),w.signal;try{if(dy(e)){let t=await fy({params:e,agent:j,sessionId:d,eventDispatcher:i,appendEntry:E,abortSignal:w.signal});return R=t.text,S(),Z_({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:R,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let t=await v.persistInitialUserEntry(s);B=t,c=t||c;try{await Vn(e.dataDir,d,{storeName:e.sessionStoreName},()=>Fr(e.dataDir,d,{storeName:e.sessionStoreName}))}catch(e){if(!(e instanceof Rn))throw e}}await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let r=await W(e.dataDir,d,{storeName:e.sessionStoreName}),o=!1,l=null;if(r?.status===`active`)try{l=await kr(e.dataDir,d,{storeName:e.sessionStoreName})}catch(e){if(e instanceof Rn)o=!0;else throw e}let u=!!(o||l&&Br(l)),p=Ur({hookRegistry:g,isGateActive:()=>u}),m=await Lr(e.dataDir,d,O,{storeName:e.sessionStoreName}),_;if(o){let e=[`<goal_context>`,`Goal workflow state (goal/state.json) is corrupt and unreadable.`,`Do not submit goal complete or blocked until the workflow state is repaired by the runtime.`,`</goal_context>`,``].join(`
192
192
  `);_={prompt:typeof m.prompt==`string`?e+m.prompt:[{type:`text`,text:e},...m.prompt],hadFirstGoalWorkflowSteering:!0}}else _=await Ir(e.dataDir,d,m.prompt,{storeName:e.sessionStoreName});K.info(`first agent turn started`,{sessionId:d,modelId:M});let x=await Uh({agent:j,message:_.prompt,continueFromHistory:!!e.uiToolResume,sessionId:d,channel:e.channel,modelId:M,historyMessages:A.historyMessages,eventDispatcher:i,hooks:g,hookCtx:h,abortSignal:w.signal,retry:e.llmRetry,artifactAccumulator:a,onTurnRecordProduced:async(e,t)=>{e&&await E(e);for(let e of t)await E(e)}});p(),R=x.text,L.add(x.inputTokens,x.outputTokens),x.error&&(z=x.error),m.hadObjectiveUpdatedSteering&&!x.error&&await Rr(e.dataDir,d,{storeName:e.sessionStoreName}),await i.dispatchDiagnostic(d,{level:x.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!x.error,error:x.error,inputTokens:x.inputTokens,outputTokens:x.outputTokens}});let C={sessionId:d,hasError:!!x.error,error:x.error,inputTokens:x.inputTokens,outputTokens:x.outputTokens};x.error?K.warn(`first agent turn completed with error`,C):K.info(`first agent turn completed`,C);let T=await uy(e.dataDir,d,V,L.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`});T.budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),K.info(`announce loop started`,{sessionId:d});let D=await Yv({agent:j,registry:t,sessionId:d,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,retry:e.llmRetry,artifactAccumulator:a,appendEntry:E});if(D.text&&(R=D.text),L.add(D.inputTokens,D.outputTokens),D.error&&!z&&(z=D.error),await i.dispatchDiagnostic(d,{level:D.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!D.error,error:D.error,inputTokens:D.inputTokens,outputTokens:D.outputTokens}}),T=await uy(e.dataDir,d,V,L.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`}),T.budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),Ar()){let n=new Or;n.reset(),x.error&&(n.lastTurnHadOutput=!1);let r=!0,o=Dt;for(;r&&n.continuationCount<o&&!w.signal.aborted;)if(r=await Nr({agent:j,dataDir:e.dataDir,sessionId:d,sessionStoreName:e.sessionStoreName,state:n,accounting:V,abortSignal:w.signal,executeTurn:async t=>{let n=await Uh({agent:j,message:t,continueFromHistory:!1,sessionId:d,channel:e.channel,modelId:M,historyMessages:A.historyMessages,eventDispatcher:i,hooks:g,hookCtx:h,abortSignal:w.signal,artifactAccumulator:a,onTurnRecordProduced:async(e,t)=>{await Pr(E,e,t)}});L.add(n.inputTokens,n.outputTokens),R=n.text||R,n.error&&!z&&(z=n.error);let r=n.turnRecords.reduce((e,t)=>e+t.toolResults.length,0);return{text:n.text,inputTokens:n.inputTokens,outputTokens:n.outputTokens,error:n.error,toolResultCount:r}},flushAccountingAfterTurn:async()=>{(await uy(e.dataDir,d,V,L.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),r){let e=await Yv({agent:j,registry:t,sessionId:d,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,artifactAccumulator:a,appendEntry:E});L.add(e.inputTokens,e.outputTokens),e.text&&(R=e.text),e.error&&!z&&(z=e.error)}}do{if(w.signal.aborted)break;if(b++,b>8){i.dispatchDiagnostic(d,{level:`warn`,scope:`runner`,phase:`bridge_cycle_limit`,message:`SessionRuntimeBridge exceeded max cycles (8)`}).catch(()=>{});break}await U_({sessionId:d,result:{sessionId:d,text:R??``,usage:L.snapshot(),durationMs:Date.now()-n,error:z},runParams:e,hookRegistry:g,hookContext:h,eventDispatcher:i});let r=await Fy({runtimeBridge:y,agent:A.agent,runtime:A,sessionId:d,channel:e.channel,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,retry:e.llmRetry,appendEntry:E,runParams:e,registry:t});L.add(r.inputTokens,r.outputTokens),r.lastResponseText&&(R=r.lastResponseText),r.error&&!z&&(z=r.error)}while(!w.signal.aborted&&(y.hasPendingMessages()||y.hasPendingCompact()));S();let k={sessionId:d,hasError:!!D.error,error:D.error,inputTokens:D.inputTokens,outputTokens:D.outputTokens};D.error?K.warn(`announce loop completed with error`,k):K.info(`announce loop completed`,k)}catch(t){if(_o(t)){let r=t,o=e.subagentContext?.parentSessionId??d,c=o===r.request.sessionId?r.request:{...r.request,sessionId:o};await it(e.dataDir,o,c,r.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},r.toolContext),await i.dispatchProgress(o,{type:`hitl_requested`,request:c}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${r.request.kind} — ${r.request.title}`,details:{requestId:c.requestId,kind:c.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),K.info(`agent paused for HITL`,{sessionId:d,requestId:c.requestId,kind:c.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let l={...L.snapshot()};return await Ly({runtime:A,resolvedModelId:M,usage:l,currentUserEntryCoveredByUsage:B}),S(),Z_({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:R||`[HITL paused] ${r.request.title}: ${r.request.prompt}`,usage:l,error:void 0,paused:{requestId:c.requestId,kind:c.kind,title:c.title}})}if(Ie(t)){let r=t,o=r.request.outputSchema.properties??{};await oy(e.dataDir,d,r.request,$(e)),await i.dispatchProgress(d,{type:`ui_tool_request`,request:r.request}),await i.dispatchDiagnostic(d,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${r.request.toolName}`,details:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(o).length}}),K.info(`agent paused for UI tool input`,{sessionId:d,requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(o).length});let c={...L.snapshot()};return await Ly({runtime:A,resolvedModelId:M,usage:c,currentUserEntryCoveredByUsage:B}),S(),Z_({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:R||``,usage:c,error:void 0,uiToolPending:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchema:r.request.outputSchema,extra:r.request.extra}})}if(P&&Uy(t))z=`Run timed out after ${N}ms`;else throw await ny({dispatcher:i,sessionId:d,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:f}}),K.error(`agent run failed`,{sessionId:d,channel:e.channel,isNewSession:f,error:t instanceof Error?t.message:String(t)}),t}finally{F!==void 0&&clearTimeout(F);try{await uy(e.dataDir,d,V,L.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}V.clearActiveGoal(),lh(d);try{A.processRegistry.disposeAll()}catch{}try{ze.disposeForDataDir(e.dataDir)}catch{}v.stop(),S()}let H=L.snapshot();P&&(z=`Run timed out after ${N}ms`),await i.dispatchDiagnostic(d,{level:z?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:H.input,outputTokens:H.output,totalTokens:H.total,hasError:!!z,error:z}});let U={sessionId:d,durationMs:Date.now()-n,inputTokens:H.input,outputTokens:H.output,totalTokens:H.total,hasError:!!z,error:z};return z?K.warn(`agent run completed with error`,U):K.info(`agent run completed`,U),await Ly({runtime:A,resolvedModelId:M,usage:H,currentUserEntryCoveredByUsage:B}),await m_({sessionId:d,runParams:T.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:C,result:{text:R,usage:H,durationMs:Date.now()-n,error:z}}),Z_({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),transcriptStartIndex:C,text:R,usage:H,error:z,sessionEndOnly:b>0})}async function Ly(e){let{runtime:t,resolvedModelId:n,usage:r,currentUserEntryCoveredByUsage:i}=e;r.input<=0&&r.total<=0||await t.contextManager.recordModelUsage({model:n,inputTokens:r.input,outputTokens:r.output,totalTokens:r.total,coveredTranscriptEntryCount:t.usageBaselineTranscriptEntryCount+(i?1:0)})}async function Ry(e){let t=Date.now(),i=new Na(e),a=Vv(e),o=a.transcriptMessage.trim()||`CRON task`,c=Ny;K.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...Py(e)});let l=a.requestedSessionId,d=!l;l?(await n(e.dataDir,l,{storeName:c})||(d=!0),await v(e.dataDir,l,{storeName:c})):l=await T(e.dataDir,e.channel,{storeName:c}),d&&await p(e.dataDir,Yp({sessionId:l,title:V_(o),channel:e.channel}),{storeName:c});let f=r(e.dataDir,l,{storeName:c});de(e.dataDir,{messageId:e.messageId,sessionId:l,sessionStoreName:c,sessionDir:f});let m={parentSessionId:l,parentDir:f},g=await T(e.dataDir,e.channel,{storeName:Ny,subagent:m});await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:g,task:o}),K.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:g,taskLength:o.length,taskPreview:ie(o)});let y={...e,sessionId:g,sessionStoreName:Ny,sessionPathScope:{subagent:m},subagentContext:{depth:1,parentSessionId:l}},b,x=`done`;try{b=await Iy(y,new Ap),b.error&&(x=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);b={sessionId:g,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:_(e.dataDir,g,{storeName:Ny,subagent:m}),toolResultsDir:s(e.dataDir,g,{storeName:Ny,subagent:m})}},x=`error`,K.error(`cron child run failed`,{parentSessionId:l,childSessionId:g,error:r})}de(e.dataDir,{messageId:e.messageId,sessionId:l,sessionStoreName:c,sessionDir:f}),await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:g,task:o,status:x}),K.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:g,status:x,durationMs:Date.now()-t,hasError:!!b.error});let C=Pp({task:o,status:x,result:b.text,error:b.error}),w=new Date().toISOString();await h(e.dataDir,l,{role:`assistant`,content:C,timestamp:w,source:`cron`},{storeName:c});let E={task:o,status:x,content:C,childSessionId:g,createdAt:w};return await S(e.dataDir,l,E,{storeName:c}),await F(e.dataDir,l,e=>zy(e,8),{storeName:c}),await u(e.dataDir,l,{},{storeName:c}),{...b,sessionId:l,context:{snapshotPath:_(e.dataDir,l,{storeName:c}),toolResultsDir:s(e.dataDir,l,{storeName:c})}}}function zy(e,t){if(t<=0)return e.filter(e=>!By(e));let n=e.reduce((e,t,n)=>(By(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!By(e)||r.has(t))}function By(e){return`source`in e&&e.source===`cron`}async function Vy(e,t){let n=async()=>{if(K.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...Py(e)}),e.channel===`CRON`&&!e.subagentContext)return Ry(e);let n=t??new Ap;try{return await Iy(e,n)}catch(t){throw e.onProgress&&await e.onProgress({type:`diagnostic`,level:`error`,scope:`runner`,phase:`run_crashed`,message:`agent run crashed before completion`,details:ty(t)}),K.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}};try{return await(e.onLog?we(e.onLog,n):n())}finally{await Te()}}function Hy(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Uy(e){if(e instanceof Error)return e.name===`AbortError`||e.message===`aborted`;if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`AbortError`||t.message===`aborted`||t.code===`aborted`}const Wy={"AGENTS.md":`---
@@ -207,7 +207,6 @@ declare class MemoryIndexManager {
207
207
  private withTimeout;
208
208
  private ensureWatcher;
209
209
  private scheduleWatchSync;
210
- private ensureSessionListener;
211
210
  private scheduleSessionDirty;
212
211
  private processSessionDeltaBatch;
213
212
  private updateSessionDelta;
@@ -317,6 +316,7 @@ type ReadonlyTranscriptSessionAdapter = {
317
316
  type PluginHookAgentContext = {
318
317
  agentId?: string;
319
318
  sessionId?: string;
319
+ messageId?: string;
320
320
  workspaceDir?: string;
321
321
  channel?: AgentRunParams["channel"];
322
322
  signal?: AbortSignal;
@@ -1,4 +1,4 @@
1
- import { C as TranscriptEntry, Hn as PluginHookRegistry, i as preloadExtensions, ln as RunEventDispatcher, mn as PluginHookAgentContext, n as discoverPiExtensions, o as PluginToolRegistry, r as getExtensions, t as DiscoveredPiExtension } from "../loader-D9_1WNPg.js";
1
+ import { C as TranscriptEntry, Hn as PluginHookRegistry, i as preloadExtensions, ln as RunEventDispatcher, mn as PluginHookAgentContext, n as discoverPiExtensions, o as PluginToolRegistry, r as getExtensions, t as DiscoveredPiExtension } from "../loader-CGp_n4m8.js";
2
2
  import { Agent, AgentTool } from "@earendil-works/pi-agent-core";
3
3
 
4
4
  //#region src/pi-extensions/tool-adapter.d.ts
@@ -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){if(e.includes(`..`)||e.startsWith(`/`))throw Error(`Invalid session id: ${e}`)}function m(e,n){return t.join(e,`.aimax`,d(n?.storeName))}function h(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(m(e,r),n,`subagents`,i)}return t.join(m(e,r),i)}function g(e,n,r){return p(n),t.join(h(e,n,r),`transcript.jsonl`)}function _(e,n,r){return p(n),t.join(h(e,n,r),`system-prompt.txt`)}async function v(e,t,n){return r(_(e,t,n))}function y(e,n,r){return t.join(h(e,n,r),`artifacts.json`)}function b(e,n,r){return t.join(h(e,n,r),`session.json`)}function x(e,n,r){return t.join(h(e,n,r),`context.json`)}function S(e,n,r){return t.join(h(e,n,r),`session-memory.json`)}function C(e,n,r){return t.join(h(e,n,r),`collapse-log.jsonl`)}function w(e,n,r){return t.join(h(e,n,r),`tool-results`)}function T(e,n,r){return t.join(h(e,n,r),`cron-executions.jsonl`)}const E={version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}};async function D(r,i,a){let o=a?.sessionId??n(),s=h(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 O(t,n,r){let i=h(t,n,r);await e.mkdir(i,{recursive:!0})}async function k(e,t,n){let i=await r(g(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 A(e,t,n,r){await O(e,t,r);let i=y(e,t,r),a=r?.encryptSessions??!1;await I(i,async()=>{let e=await N(i);await F(i,{version:1,updatedAt:new Date().toISOString(),operations:[...e.operations,M(n)]},a)})}async function j(e,t,n){return(await N(y(e,t,n))).operations}function M(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 N(e){let t=await r(e);if(t===null)return P();try{let e=JSON.parse(t);return e.version!==1||!Array.isArray(e.operations)?P():{version:1,updatedAt:typeof e.updatedAt==`string`?e.updatedAt:new Date(0).toISOString(),operations:e.operations}}catch{return P()}}function P(){return{version:1,updatedAt:new Date(0).toISOString(),operations:[]}}async function F(n,r,i){await e.mkdir(t.dirname(n),{recursive:!0}),await o(n,`${JSON.stringify(r,null,2)}\n`,i)}async function I(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 L(e,n,r,i){await O(e,n,i);let o=g(e,n,i);await a(o,JSON.stringify(r)+`
3
- `,i?.encryptSessions??!1);try{let{resolveMemoryProviderOrDefault:n}=await import(`./default-provider-DchVtHkL.js`).then(e=>e.n),r=t.join(e,`.aimax`),a=n({providerId:i?.providerId,pluginId:i?.pluginId,dataDir:e,memoryDir:r,sessionStoreName:i?.storeName});a.provider.noteSessionUpdate&&a.provider.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 R(e,n,r,a){await O(e,n,a);let o=g(e,n,a),s=r(await k(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{resolveMemoryProviderOrDefault:n}=await import(`./default-provider-DchVtHkL.js`).then(e=>e.n),r=t.join(e,`.aimax`),i=n({providerId:a?.providerId,pluginId:a?.pluginId,dataDir:e,memoryDir:r,sessionStoreName:a?.storeName});i.provider.noteSessionUpdate&&i.provider.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 z(e,t,n,r){await O(e,t,r),await a(T(e,t,r),JSON.stringify(n)+`
3
+ `,i?.encryptSessions??!1);try{let{resolveMemoryProviderOrDefault:n}=await import(`./default-provider-BV9gmV00.js`).then(e=>e.n),r=t.join(e,`.aimax`),a=n({providerId:i?.providerId,pluginId:i?.pluginId,dataDir:e,memoryDir:r,sessionStoreName:i?.storeName});a.provider.noteSessionUpdate&&a.provider.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 R(e,n,r,a){await O(e,n,a);let o=g(e,n,a),s=r(await k(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{resolveMemoryProviderOrDefault:n}=await import(`./default-provider-BV9gmV00.js`).then(e=>e.n),r=t.join(e,`.aimax`),i=n({providerId:a?.providerId,pluginId:a?.pluginId,dataDir:e,memoryDir:r,sessionStoreName:a?.storeName});i.provider.noteSessionUpdate&&i.provider.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 z(e,t,n,r){await O(e,t,r),await a(T(e,t,r),JSON.stringify(n)+`
5
5
  `,r?.encryptSessions??!1)}async function B(e,t,n){let i=await r(T(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 V(t,n){let r=m(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 H(e,t,n){await O(e,t.id,n);let r=b(e,t.id,n),a=n?.encryptSessions??!1;await i(r,JSON.stringify(t,null,2),a)}async function U(e,t,n,r){let i=await W(e,t,r);if(!i)return null;let a={...i,...n,id:i.id,createdAt:i.createdAt,updatedAt:new Date().toISOString()};return await H(e,a,r),a}async function W(n,i,a){let o=await r(b(n,i,a));if(o===null)return null;try{let r=JSON.parse(o);if(!r.channel){let o=t.join(h(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 G(e,t,n){let r=await V(e,n),i=await Promise.all(r.map(async t=>{let r=await W(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 K(e,t,n){let i=await r(x(e,t,n));if(i===null)return E;try{let e=JSON.parse(i),t=typeof e.version==`number`?e.version:void 0;return t!==1&&t!==2?E:{version:2,updatedAt:typeof e.updatedAt==`string`?e.updatedAt:E.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 E}}async function q(t,n,r){let i=h(t,n,r);try{return(await e.stat(i)).isDirectory()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function J(t,n,r){let i=b(t,n,r);try{return(await e.stat(i)).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Y(e,t,n){let[r,i,a]=await Promise.all([W(e,t,n),k(e,t,n),K(e,t,n)]);return{id:t,metadata:r,transcriptPath:g(e,t,n),contextSnapshotPath:x(e,t,n),sessionMemoryPath:S(e,t,n),collapseLogPath:C(e,t,n),toolResultsDir:w(e,t,n),transcriptEntryCount:i.length,readStateCount:a.readStates.length,toolResultRefCount:a.toolResults.length,transcriptEntries:i,context:a}}async function X(e,t,n){let r=await Y(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{m as A,d as C,q as D,h as E,a as F,o as I,r as L,w as M,g as N,S as O,U as P,s as R,b as S,H as T,B as _,L as a,v as b,x as c,O as d,X as f,j as g,V as h,z as i,_ as j,J as k,D as l,G as m,l as n,y as o,Y as p,A as r,C as s,c as t,T as u,K as v,R as w,k as x,W as y,i as z};
@@ -1,3 +1,3 @@
1
- import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{E as t,F as n,L as r,z as i}from"./session-CvZsdTZJ.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,n,r){return o.join(t(e,n,r),`pending-hitl.json`)}function l(e,n,r){return o.join(t(e,n,r),`hitl-history.jsonl`)}async function u(e,n,r,o){let s=t(e,n,o);await a.mkdir(s,{recursive:!0});let l=c(e,n,o),u=o?.encryptSessions??!1;await i(l,JSON.stringify(r,null,2),u)}async function d(e,r,i,o){let s=t(e,r,o);await a.mkdir(s,{recursive:!0}),await n(l(e,r,o),JSON.stringify(i)+`
1
+ import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{E as t,F as n,L as r,z as i}from"./session-BpKaF-Gk.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,n,r){return o.join(t(e,n,r),`pending-hitl.json`)}function l(e,n,r){return o.join(t(e,n,r),`hitl-history.jsonl`)}async function u(e,n,r,o){let s=t(e,n,o);await a.mkdir(s,{recursive:!0});let l=c(e,n,o),u=o?.encryptSessions??!1;await i(l,JSON.stringify(r,null,2),u)}async function d(e,r,i,o){let s=t(e,r,o);await a.mkdir(s,{recursive:!0}),await n(l(e,r,o),JSON.stringify(i)+`
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};
@@ -1,4 +1,4 @@
1
- import { $t as PluginManifestRegistry, Bn as PluginHookName, Hn as PluginHookRegistry, Pn as PluginHookHandlerMap, Yt as PluginsConfig, c as PluginUiToolOptions, cn as PluginOrigin, ir as MemoryProviderFactory, it as LlmApiFormat, mn as PluginHookAgentContext, o as PluginToolRegistry, qt as NormalizedPluginsConfig, rn as PluginDiagnostic, s as PluginUiToolDescriptor, t as DiscoveredPiExtension } from "./loader-D9_1WNPg.js";
1
+ import { $t as PluginManifestRegistry, Bn as PluginHookName, Hn as PluginHookRegistry, Pn as PluginHookHandlerMap, Yt as PluginsConfig, c as PluginUiToolOptions, cn as PluginOrigin, ir as MemoryProviderFactory, it as LlmApiFormat, mn as PluginHookAgentContext, o as PluginToolRegistry, qt as NormalizedPluginsConfig, rn as PluginDiagnostic, s as PluginUiToolDescriptor, t as DiscoveredPiExtension } from "./loader-CGp_n4m8.js";
2
2
  import { AgentProgressEvent } from "@gencode/shared";
3
3
 
4
4
  //#region src/plugins/runtime.d.ts
@@ -1,2 +1,2 @@
1
- import { n as SystemWarmState, r as prepareSystemRuntime, t as PrepareSystemRuntimeOptions } from "./system-runtime-Bi5ESko9.js";
1
+ import { n as SystemWarmState, r as prepareSystemRuntime, t as PrepareSystemRuntimeOptions } from "./system-runtime-Bop42Cc_.js";
2
2
  export { PrepareSystemRuntimeOptions, SystemWarmState, prepareSystemRuntime };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/agents",
3
- "version": "0.16.1",
3
+ "version": "0.16.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",