@gencode/agents 0.0.44 → 0.0.46
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.
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{createRequire as t}from"node:module";import n from"node:fs/promises";import r from"node:path";import i,{randomUUID as a}from"node:crypto";import o from"node:fs";const s=`sessions`;function c(e){let t=e?.trim()||s;if(!/^[A-Za-z0-9_-]+$/.test(t))throw Error(`Invalid session store name: ${e}. Must match /^[A-Za-z0-9_-]+$/`);return t}function l(e,t){return r.join(e,`.aimax`,c(t?.storeName))}function u(e,t,n){return r.join(l(e,n),t)}function d(e,t,n){return r.join(u(e,t,n),`transcript.jsonl`)}function f(e,t,n){return r.join(u(e,t,n),`session.json`)}function p(e,t,n){return r.join(u(e,t,n),`context.json`)}function m(e,t,n){return r.join(u(e,t,n),`session-memory.json`)}function h(e,t,n){return r.join(u(e,t,n),`collapse-log.jsonl`)}function g(e,t,n){return r.join(u(e,t,n),`tool-results`)}const _={version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}};async function ee(e,t,i){let o=a(),s=u(e,o,i);await n.mkdir(s,{recursive:!0});let c=r.join(s,`.channel`);return await n.writeFile(c,t,`utf-8`),o}async function v(e,t,r){let i=u(e,t,r);await n.mkdir(i,{recursive:!0})}async function y(e,t,r){let i=d(e,t,r),a;try{a=await n.readFile(i,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let o=[];for(let e of a.split(`
|
|
2
2
|
`)){let t=e.trim();if(t)try{o.push(JSON.parse(t))}catch{}}return o}async function b(e,t,i,a){await v(e,t,a);let o=d(e,t,a),s=JSON.stringify(i)+`
|
|
3
3
|
`;await n.appendFile(o,s,`utf-8`);try{let{resolveMemoryProvider:t}=await import(`./provider-registry-CxtHsHdk.js`).then(e=>e.t),{createBuiltinMemoryProvider:n}=await Promise.resolve().then(()=>Q),i=r.join(e,`.aimax`),s=t({providerId:a?.providerId,pluginId:a?.pluginId,dataDir:e,memoryDir:i,sessionStoreName:a?.storeName})?.provider??n({dataDir:e,memoryDir:i,sessionStoreName:a?.storeName});s.noteSessionUpdate&&s.noteSessionUpdate(o)}catch{}a?.onMemoryChanged&&await Promise.resolve(a.onMemoryChanged({reason:`transcript-append`,files:[r.join(c(a.storeName),t,`transcript.jsonl`).replace(/\\/g,`/`)],source:`sessions`,sessionId:t,providerId:a.providerId??a.pluginId,timestamp:new Date().toISOString()})).catch(()=>{})}async function te(e,t,i,a){await v(e,t,a);let o=d(e,t,a),s=i(await y(e,t,a)),l=s.map(e=>JSON.stringify(e)).join(`
|
|
4
|
-
`);await n.writeFile(o,l.length>0?`${l}\n`:``,`utf-8`);try{let{resolveMemoryProvider:t}=await import(`./provider-registry-CxtHsHdk.js`).then(e=>e.t),{createBuiltinMemoryProvider:n}=await Promise.resolve().then(()=>Q),i=r.join(e,`.aimax`),s=t({providerId:a?.providerId,pluginId:a?.pluginId,dataDir:e,memoryDir:i,sessionStoreName:a?.storeName})?.provider??n({dataDir:e,memoryDir:i,sessionStoreName:a?.storeName});s.noteSessionUpdate&&s.noteSessionUpdate(o)}catch{}return a?.onMemoryChanged&&await Promise.resolve(a.onMemoryChanged({reason:`transcript-rewrite`,files:[r.join(c(a.storeName),t,`transcript.jsonl`).replace(/\\/g,`/`)],source:`sessions`,sessionId:t,providerId:a.providerId??a.pluginId,timestamp:new Date().toISOString()})).catch(()=>{}),s}async function x(e,t){let r=l(e,t);try{return(await n.readdir(r,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function S(e,t,r){await v(e,t.id,r);let i=f(e,t.id,r);await n.writeFile(i,JSON.stringify(t,null,2),`utf-8`)}async function ne(e,t,n,r){let i=await C(e,t,r);if(!i)return null;let a={...i,...n,id:i.id,createdAt:i.createdAt,updatedAt:new Date().toISOString()};return await S(e,a,r),a}async function C(e,t,i){let a=f(e,t,i);try{let o=await n.readFile(a,`utf-8`),s=JSON.parse(o);if(!s.channel){let a=r.join(u(e,t,i),`.channel`);try{s.channel=(await n.readFile(a,`utf-8`)).trim()}catch{s.channel=`WEB`}}return s}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function re(e,t,n){let r=await x(e,n),i=await Promise.all(r.map(async t=>{let r=await C(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 w(e,t,r){let i=p(e,t,r);try{let e=await n.readFile(i,`utf-8`),t=JSON.parse(e),r=typeof t.version==`number`?t.version:void 0;return r!==1&&r!==2?_:{version:2,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:_.updatedAt,readStates:Array.isArray(t.readStates)?t.readStates:[],toolResults:Array.isArray(t.toolResults)?t.toolResults:[],compaction:{sessionMemory:t.compaction?.sessionMemory,budgets:Array.isArray(t.compaction?.budgets)?t.compaction.budgets:[],snips:Array.isArray(t.compaction?.snips)?t.compaction.snips:[],collapseSpans:Array.isArray(t.compaction?.collapseSpans)?t.compaction.collapseSpans:[],consecutiveAutocompactFailures:typeof t.compaction?.consecutiveAutocompactFailures==`number`?t.compaction.consecutiveAutocompactFailures:0,lastCompactionAt:typeof t.compaction?.lastCompactionAt==`string`?t.compaction.lastCompactionAt:void 0,lastCompactionLayer:t.compaction?.lastCompactionLayer===`L1`||t.compaction?.lastCompactionLayer===`L2`||t.compaction?.lastCompactionLayer===`L3`||t.compaction?.lastCompactionLayer===`L4`||t.compaction?.lastCompactionLayer===`L5`||t.compaction?.lastCompactionLayer===`L6`?t.compaction.lastCompactionLayer:void 0}}}catch(e){if(e.code===`ENOENT`)return _;throw e}}async function T(e,t,n){let[r,i,a]=await Promise.all([C(e,t,n),y(e,t,n),w(e,t,n)]);return{id:t,metadata:r,transcriptPath:d(e,t,n),contextSnapshotPath:p(e,t,n),sessionMemoryPath:m(e,t,n),collapseLogPath:h(e,t,n),toolResultsDir:g(e,t,n),transcriptEntryCount:i.length,readStateCount:a.readStates.length,toolResultRefCount:a.toolResults.length,transcriptEntries:i,context:a}}async function E(e,t,n){let r=await T(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}}}function D(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}async function ie(e){let t;try{t=await n.lstat(e)}catch(e){if(D(e))return{missing:!0};throw e}if(t.isSymbolicLink()||!t.isFile())throw Error(`path required`);return{missing:!1,stat:t}}function ae(e){try{o.mkdirSync(e,{recursive:!0})}catch{}return e}function oe(e){return e.trim().replace(/^[./]+/,``).replace(/\\/g,`/`)}function se(e){let t=oe(e);return t?t===`MEMORY.md`||t===`memory.md`?!0:t.startsWith(`memory/`):!1}async function O(e,t){let i=await n.readdir(e,{withFileTypes:!0});for(let n of i){let i=r.join(e,n.name);if(!n.isSymbolicLink()){if(n.isDirectory()){await O(i,t);continue}n.isFile()&&n.name.endsWith(`.md`)&&t.push(i)}}}async function k(e){let t=[],i=r.join(e,`MEMORY.md`),a=r.join(e,`memory.md`),o=r.join(e,`memory`),s=async e=>{try{let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||!e.endsWith(`.md`))return;t.push(e)}catch{}};await s(i),await s(a);try{let e=await n.lstat(o);!e.isSymbolicLink()&&e.isDirectory()&&await O(o,t)}catch{}if(t.length<=1)return t;let c=new Set,l=[];for(let e of t){let t=e;try{t=await n.realpath(e)}catch{}c.has(t)||(c.add(t),l.push(e))}return l}function A(e){return i.createHash(`sha256`).update(e).digest(`hex`)}async function ce(e,t){let i;try{i=await n.stat(e)}catch(e){if(D(e))return null;throw e}let a;try{a=await n.readFile(e,`utf-8`)}catch(e){if(D(e))return null;throw e}let o=A(a);return{path:r.relative(t,e).replace(/\\/g,`/`),absPath:e,mtimeMs:i.mtimeMs,size:i.size,hash:o}}function le(e,t){let n=e.split(`
|
|
4
|
+
`);await n.writeFile(o,l.length>0?`${l}\n`:``,`utf-8`);try{let{resolveMemoryProvider:t}=await import(`./provider-registry-CxtHsHdk.js`).then(e=>e.t),{createBuiltinMemoryProvider:n}=await Promise.resolve().then(()=>Q),i=r.join(e,`.aimax`),s=t({providerId:a?.providerId,pluginId:a?.pluginId,dataDir:e,memoryDir:i,sessionStoreName:a?.storeName})?.provider??n({dataDir:e,memoryDir:i,sessionStoreName:a?.storeName});s.noteSessionUpdate&&s.noteSessionUpdate(o)}catch{}return a?.onMemoryChanged&&await Promise.resolve(a.onMemoryChanged({reason:`transcript-rewrite`,files:[r.join(c(a.storeName),t,`transcript.jsonl`).replace(/\\/g,`/`)],source:`sessions`,sessionId:t,providerId:a.providerId??a.pluginId,timestamp:new Date().toISOString()})).catch(()=>{}),s}async function x(e,t){let r=l(e,t);try{return(await n.readdir(r,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function S(e,t,r){await v(e,t.id,r);let i=f(e,t.id,r);await n.writeFile(i,JSON.stringify(t,null,2),`utf-8`)}async function ne(e,t,n,r){let i=await C(e,t,r);if(!i)return null;let a={...i,...n,id:i.id,createdAt:i.createdAt,updatedAt:new Date().toISOString()};return await S(e,a,r),a}async function C(e,t,i){let a=f(e,t,i);try{let o=await n.readFile(a,`utf-8`),s=JSON.parse(o);if(!s.channel){let a=r.join(u(e,t,i),`.channel`);try{s.channel=(await n.readFile(a,`utf-8`)).trim()}catch{s.channel=`WEB`}}return s}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function re(e,t,n){let r=await x(e,n),i=await Promise.all(r.map(async t=>{let r=await C(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 w(e,t,r){let i=p(e,t,r);try{let e=await n.readFile(i,`utf-8`),t=JSON.parse(e),r=typeof t.version==`number`?t.version:void 0;return r!==1&&r!==2?_:{version:2,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:_.updatedAt,readStates:Array.isArray(t.readStates)?t.readStates:[],toolResults:Array.isArray(t.toolResults)?t.toolResults:[],compaction:{sessionMemory:t.compaction?.sessionMemory,modelUsage:t.compaction?.modelUsage,budgets:Array.isArray(t.compaction?.budgets)?t.compaction.budgets:[],snips:Array.isArray(t.compaction?.snips)?t.compaction.snips:[],collapseSpans:Array.isArray(t.compaction?.collapseSpans)?t.compaction.collapseSpans:[],consecutiveAutocompactFailures:typeof t.compaction?.consecutiveAutocompactFailures==`number`?t.compaction.consecutiveAutocompactFailures:0,lastCompactionAt:typeof t.compaction?.lastCompactionAt==`string`?t.compaction.lastCompactionAt:void 0,lastCompactionLayer:t.compaction?.lastCompactionLayer===`L1`||t.compaction?.lastCompactionLayer===`L2`||t.compaction?.lastCompactionLayer===`L3`||t.compaction?.lastCompactionLayer===`L4`||t.compaction?.lastCompactionLayer===`L5`||t.compaction?.lastCompactionLayer===`L6`?t.compaction.lastCompactionLayer:void 0}}}catch(e){if(e.code===`ENOENT`)return _;throw e}}async function T(e,t,n){let[r,i,a]=await Promise.all([C(e,t,n),y(e,t,n),w(e,t,n)]);return{id:t,metadata:r,transcriptPath:d(e,t,n),contextSnapshotPath:p(e,t,n),sessionMemoryPath:m(e,t,n),collapseLogPath:h(e,t,n),toolResultsDir:g(e,t,n),transcriptEntryCount:i.length,readStateCount:a.readStates.length,toolResultRefCount:a.toolResults.length,transcriptEntries:i,context:a}}async function E(e,t,n){let r=await T(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}}}function D(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}async function ie(e){let t;try{t=await n.lstat(e)}catch(e){if(D(e))return{missing:!0};throw e}if(t.isSymbolicLink()||!t.isFile())throw Error(`path required`);return{missing:!1,stat:t}}function ae(e){try{o.mkdirSync(e,{recursive:!0})}catch{}return e}function oe(e){return e.trim().replace(/^[./]+/,``).replace(/\\/g,`/`)}function se(e){let t=oe(e);return t?t===`MEMORY.md`||t===`memory.md`?!0:t.startsWith(`memory/`):!1}async function O(e,t){let i=await n.readdir(e,{withFileTypes:!0});for(let n of i){let i=r.join(e,n.name);if(!n.isSymbolicLink()){if(n.isDirectory()){await O(i,t);continue}n.isFile()&&n.name.endsWith(`.md`)&&t.push(i)}}}async function k(e){let t=[],i=r.join(e,`MEMORY.md`),a=r.join(e,`memory.md`),o=r.join(e,`memory`),s=async e=>{try{let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||!e.endsWith(`.md`))return;t.push(e)}catch{}};await s(i),await s(a);try{let e=await n.lstat(o);!e.isSymbolicLink()&&e.isDirectory()&&await O(o,t)}catch{}if(t.length<=1)return t;let c=new Set,l=[];for(let e of t){let t=e;try{t=await n.realpath(e)}catch{}c.has(t)||(c.add(t),l.push(e))}return l}function A(e){return i.createHash(`sha256`).update(e).digest(`hex`)}async function ce(e,t){let i;try{i=await n.stat(e)}catch(e){if(D(e))return null;throw e}let a;try{a=await n.readFile(e,`utf-8`)}catch(e){if(D(e))return null;throw e}let o=A(a);return{path:r.relative(t,e).replace(/\\/g,`/`),absPath:e,mtimeMs:i.mtimeMs,size:i.size,hash:o}}function le(e,t){let n=e.split(`
|
|
5
5
|
`);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(`
|
|
6
6
|
`),r=e.lineNo,i=t.lineNo;a.push({startLine:r,endLine:i,text:n,hash:A(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 ue(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 j(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function de(e,t){if(e.length===0||t.length===0)return 0;let n=Math.min(e.length,t.length),r=0,i=0,a=0;for(let o=0;o<n;o+=1){let n=e[o]??0,s=t[o]??0;r+=n*s,i+=n*n,a+=s*s}return i===0||a===0?0:r/(Math.sqrt(i)*Math.sqrt(a))}function fe(e){return(e.toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[]).filter(Boolean)}function pe(e){return i.createHash(`sha256`).update(e).digest().readUInt32BE(0)}function M(e,t=384){let n=Array(t).fill(0),r=fe(e);if(r.length===0)return n;for(let e of r){let r=pe(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 N(e){let t=e?.model?.trim()||`mock-embedding-v1`,n=e?.dimensions??384;return{id:`external-mock`,model:t,embedQuery:async e=>M(e,n),embedBatch:async e=>e.map(e=>M(e,n))}}const P=new class{providers=new Map;byPluginId=new Map;register(e){this.providers.set(e.id,e),e.pluginId&&this.byPluginId.set(e.pluginId,e.id)}getById(e){return this.providers.get(e)}getByPluginId(e){let t=this.byPluginId.get(e);return t?this.providers.get(t):void 0}clear(){this.providers.clear(),this.byPluginId.clear()}};function me(e){let t=e.id?.trim()||e.pluginId;return P.register({id:t,pluginId:e.pluginId,create:e.create,config:e.config,rootDir:e.rootDir,source:e.source}),t}function F(e){let t=e.providerId?.trim(),n=e.pluginId?.trim(),r=(t?P.getById(t):void 0)??(n?P.getByPluginId(n):void 0);return r?{provider:r.create({dataDir:e.dataDir,memoryDir:e.memoryDir,pluginId:r.pluginId,config:r.config,rootDir:r.rootDir,source:r.source}),registration:r}:null}function he(){P.clear()}const I={enabled:!1,lambda:.7};function L(e){let t=e.toLowerCase().match(/[a-z0-9_]+/g)??[];return new Set(t)}function R(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 ge(e,t,n){if(t.length===0)return 0;let r=0,i=n.get(e.id)??L(e.content);for(let e of t){let t=R(i,n.get(e.id)??L(e.content));t>r&&(r=t)}return r}function _e(e,t,n){return n*e-(1-n)*t}function ve(e,t={}){let{enabled:n=I.enabled,lambda:r=I.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,L(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=_e(l(n.score),ge(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 ye(e,t={}){if(e.length===0)return e;let n=new Map;return ve(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 z={enabled:!1,halfLifeDays:30},B=/(?:^|\/)(?:memory)\/(\d{4})-(\d{2})-(\d{2})\.md$/;function be(e){return!Number.isFinite(e)||e<=0?0:Math.LN2/e}function xe(e){let t=be(e.halfLifeDays),n=Math.max(0,e.ageInDays);return t<=0||!Number.isFinite(n)?1:Math.exp(-t*n)}function Se(e){return e.score*xe(e)}function Ce(e){let t=e.replaceAll(`\\`,`/`).replace(/^\.\//,``),n=B.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 we(e){let t=e.replaceAll(`\\`,`/`).replace(/^\.\//,``);return t===`MEMORY.md`||t===`memory.md`?!0:t.startsWith(`memory/`)?!B.test(t):!1}async function Te(e){let t=Ce(e.filePath);if(t)return t;if(e.source===`memory`&&we(e.filePath)||!e.memoryRoot)return null;let i=r.isAbsolute(e.filePath)?e.filePath:r.resolve(e.memoryRoot,e.filePath);try{let e=await n.stat(i);return Number.isFinite(e.mtimeMs)?new Date(e.mtimeMs):null}catch{return null}}function Ee(e,t){return Math.max(0,t-e.getTime())/864e5}async function De(e){let t={...z,...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=Te({filePath:i.path,source:i.source,memoryRoot:e.memoryRoot}),r.set(a,o));let s=await o;if(!s)return i;let c=Se({score:i.score,ageInDays:Ee(s,n),halfLifeDays:t.halfLifeDays});return{...i,score:c}}))}function Oe(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 ke(e){return 1/(1+(Number.isFinite(e)?Math.max(0,e):999))}async function Ae(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 De({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:{...z,...e.temporalDecay},memoryRoot:e.memoryRoot,nowMs:e.nowMs})).slice().sort((e,t)=>t.score-e.score),r={...I,...e.mmr};return r.enabled?ye(n,r):n}function je(e){e.db.exec(`
|
|
7
7
|
CREATE TABLE IF NOT EXISTS meta (
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { S as AgentsConfig, _ as saveAgentsConfig, a as listAgents, b as AgentCo
|
|
|
2
2
|
import { AssistantMessage, Message } from "@mariozechner/pi-ai";
|
|
3
3
|
import { AgentMessage, AgentTool } from "@mariozechner/pi-agent-core";
|
|
4
4
|
import * as _gencode_shared0 from "@gencode/shared";
|
|
5
|
-
import { AgentCustomProgressEvent, AgentProgressEvent, AgentProgressEvent as AgentProgressEvent$1, CallbackEventPayload, CallbackEventPayload as CallbackEventPayload$1, Channel, Channel as Channel$1, CollapseSpan, HitlCheckpoint, HitlCheckpoint as HitlCheckpoint$1, HitlHistoryEntry, HitlRequest, HitlRequest as HitlRequest$1, HitlResolution, HitlResolution as HitlResolution$1, HitlStatus, HitlToolContext, HitlToolContext as HitlToolContext$1, PausedRunState, PausedRunState as PausedRunState$1, ReadStateRecord, RunResultPayload, RunResultPayload as RunResultPayload$1, SessionContextSnapshot, SessionMemorySnapshot, SnipRecord, ToolResultReference, UiToolExtra, UiToolOutputSchema, UiToolPausedState, UiToolRequest, UiToolResult, UiToolValidationResult } from "@gencode/shared";
|
|
5
|
+
import { AgentCustomProgressEvent, AgentProgressEvent, AgentProgressEvent as AgentProgressEvent$1, CallbackEventPayload, CallbackEventPayload as CallbackEventPayload$1, Channel, Channel as Channel$1, CollapseSpan, HitlCheckpoint, HitlCheckpoint as HitlCheckpoint$1, HitlHistoryEntry, HitlRequest, HitlRequest as HitlRequest$1, HitlResolution, HitlResolution as HitlResolution$1, HitlStatus, HitlToolContext, HitlToolContext as HitlToolContext$1, ModelUsageCheckpoint, PausedRunState, PausedRunState as PausedRunState$1, ReadStateRecord, RunResultPayload, RunResultPayload as RunResultPayload$1, SessionContextSnapshot, SessionMemorySnapshot, SnipRecord, ToolResultReference, UiToolExtra, UiToolOutputSchema, UiToolPausedState, UiToolRequest, UiToolResult, UiToolValidationResult } from "@gencode/shared";
|
|
6
6
|
|
|
7
7
|
//#region src/loop-detection/tool-loop-detection.d.ts
|
|
8
8
|
type ToolLoopDetectionConfig = {
|
|
@@ -596,6 +596,7 @@ type PluginHookLlmOutputEvent = {
|
|
|
596
596
|
model: string;
|
|
597
597
|
assistantTexts: string[];
|
|
598
598
|
lastAssistant?: AssistantMessage;
|
|
599
|
+
durationMs?: number;
|
|
599
600
|
usage?: {
|
|
600
601
|
input?: number;
|
|
601
602
|
output?: number;
|
|
@@ -824,6 +825,7 @@ type SessionContextStore = {
|
|
|
824
825
|
recordSnip(record: SnipRecord): Promise<void>;
|
|
825
826
|
recordCollapse(span: CollapseSpan): Promise<void>;
|
|
826
827
|
setSessionMemory(snapshot: SessionMemorySnapshot): Promise<void>;
|
|
828
|
+
recordModelUsage(checkpoint: ModelUsageCheckpoint): Promise<void>;
|
|
827
829
|
recordAutocompactResult(params: {
|
|
828
830
|
layer: "L6";
|
|
829
831
|
failed: boolean;
|
|
@@ -852,6 +854,7 @@ type ManageLayeredHistoryParams = {
|
|
|
852
854
|
};
|
|
853
855
|
historyLimit?: number;
|
|
854
856
|
compactionEnabled?: boolean;
|
|
857
|
+
pendingUserMessage?: string;
|
|
855
858
|
signal?: AbortSignal;
|
|
856
859
|
hooks?: PluginHookRegistry;
|
|
857
860
|
hookCtx?: PluginHookAgentContext;
|
|
@@ -891,6 +894,13 @@ type ContextManager = {
|
|
|
891
894
|
thresholdChars?: number;
|
|
892
895
|
previewChars?: number;
|
|
893
896
|
}): Promise<PersistedToolResult>;
|
|
897
|
+
recordModelUsage(params: {
|
|
898
|
+
model: string;
|
|
899
|
+
inputTokens: number;
|
|
900
|
+
outputTokens: number;
|
|
901
|
+
totalTokens: number;
|
|
902
|
+
coveredTranscriptEntryCount: number;
|
|
903
|
+
}): Promise<void>;
|
|
894
904
|
manageHistory(params: Omit<ManageLayeredHistoryParams, "contextStore">): Promise<ManageLayeredHistoryResult>;
|
|
895
905
|
getSnapshot: SessionContextStore["getSnapshot"];
|
|
896
906
|
};
|
|
@@ -1308,30 +1318,6 @@ type UnionLast<U> = UnionToIntersect<U extends unknown ? (x: U) => 0 : never> ex
|
|
|
1308
1318
|
type UnionToTuple<U, Acc extends unknown[] = [], R = UnionLast<U>> = [U] extends [never] ? Acc : UnionToTuple<Exclude<U, R>, [Extract<U, R>, ...Acc]>;
|
|
1309
1319
|
type Assert<T, E> = T extends E ? T : never;
|
|
1310
1320
|
type Evaluate<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;
|
|
1311
|
-
type Ensure<T> = T extends infer U ? U : never;
|
|
1312
|
-
//#endregion
|
|
1313
|
-
//#region ../../node_modules/.pnpm/@sinclair+typebox@0.34.48/node_modules/@sinclair/typebox/build/cjs/type/array/array.d.ts
|
|
1314
|
-
interface ArrayOptions extends SchemaOptions {
|
|
1315
|
-
/** The minimum number of items in this array */
|
|
1316
|
-
minItems?: number;
|
|
1317
|
-
/** The maximum number of items in this array */
|
|
1318
|
-
maxItems?: number;
|
|
1319
|
-
/** Should this schema contain unique items */
|
|
1320
|
-
uniqueItems?: boolean;
|
|
1321
|
-
/** A schema for which some elements should match */
|
|
1322
|
-
contains?: TSchema;
|
|
1323
|
-
/** A minimum number of contains schema matches */
|
|
1324
|
-
minContains?: number;
|
|
1325
|
-
/** A maximum number of contains schema matches */
|
|
1326
|
-
maxContains?: number;
|
|
1327
|
-
}
|
|
1328
|
-
type ArrayStatic<T extends TSchema, P extends unknown[]> = Ensure<Static<T, P>[]>;
|
|
1329
|
-
interface TArray<T extends TSchema = TSchema> extends TSchema, ArrayOptions {
|
|
1330
|
-
[Kind]: 'Array';
|
|
1331
|
-
static: ArrayStatic<T, this['params']>;
|
|
1332
|
-
type: 'array';
|
|
1333
|
-
items: T;
|
|
1334
|
-
}
|
|
1335
1321
|
//#endregion
|
|
1336
1322
|
//#region ../../node_modules/.pnpm/@sinclair+typebox@0.34.48/node_modules/@sinclair/typebox/build/cjs/type/schema/schema.d.ts
|
|
1337
1323
|
interface SchemaOptions {
|
|
@@ -1633,63 +1619,6 @@ type SubagentsResult = {
|
|
|
1633
1619
|
*/
|
|
1634
1620
|
declare function createSubagentsTool(registry: SubagentRegistry, parentSessionId: string): AgentTool<typeof subagentsSchema, SubagentsResult>;
|
|
1635
1621
|
//#endregion
|
|
1636
|
-
//#region src/tools/clarify.d.ts
|
|
1637
|
-
declare const clarifySchema: TObject<{
|
|
1638
|
-
question: TString;
|
|
1639
|
-
options: TOptional<TArray<TString>>;
|
|
1640
|
-
allow_free_text: TOptional<TBoolean>;
|
|
1641
|
-
}>;
|
|
1642
|
-
type ClarifyResult = {
|
|
1643
|
-
paused: true;
|
|
1644
|
-
};
|
|
1645
|
-
/**
|
|
1646
|
-
* Creates the `clarify` tool that the agent can call to ask the user a question.
|
|
1647
|
-
*
|
|
1648
|
-
* @param sessionId - Current session ID for the HITL request.
|
|
1649
|
-
* @param hitlResume - When present, contains the user's resolution for a
|
|
1650
|
-
* previously paused clarify request. The tool returns the
|
|
1651
|
-
* user's answer instead of throwing again.
|
|
1652
|
-
*/
|
|
1653
|
-
declare function createClarifyTool(sessionId: string, hitlResume?: AgentRunParams["hitlResume"]): AgentTool<typeof clarifySchema, ClarifyResult>;
|
|
1654
|
-
//#endregion
|
|
1655
|
-
//#region src/tools/request-approval.d.ts
|
|
1656
|
-
declare const approvalSchema: TObject<{
|
|
1657
|
-
action: TString;
|
|
1658
|
-
reason: TString;
|
|
1659
|
-
details: TOptional<TString>;
|
|
1660
|
-
}>;
|
|
1661
|
-
type ApprovalResult = {
|
|
1662
|
-
paused: true;
|
|
1663
|
-
};
|
|
1664
|
-
declare function formatApprovalResolution(resolution: NonNullable<NonNullable<AgentRunParams["hitlResume"]>["resolution"]>): string;
|
|
1665
|
-
/**
|
|
1666
|
-
* Creates the `request_approval` tool.
|
|
1667
|
-
*
|
|
1668
|
-
* @param sessionId - Current session ID.
|
|
1669
|
-
* @param turnId - Current turn ID for checkpoint tracking.
|
|
1670
|
-
*/
|
|
1671
|
-
declare function createRequestApprovalTool(sessionId: string, hitlResume?: AgentRunParams["hitlResume"]): AgentTool<typeof approvalSchema, ApprovalResult>;
|
|
1672
|
-
//#endregion
|
|
1673
|
-
//#region src/tools/request-review.d.ts
|
|
1674
|
-
declare const reviewSchema: TObject<{
|
|
1675
|
-
title: TString;
|
|
1676
|
-
description: TString;
|
|
1677
|
-
content: TString;
|
|
1678
|
-
content_type: TOptional<TString>;
|
|
1679
|
-
}>;
|
|
1680
|
-
type ReviewResult = {
|
|
1681
|
-
paused: true;
|
|
1682
|
-
};
|
|
1683
|
-
/**
|
|
1684
|
-
* Creates the `request_review` tool.
|
|
1685
|
-
*
|
|
1686
|
-
* @param sessionId - Current session ID.
|
|
1687
|
-
* @param hitlResume - When present, contains the user's resolution for a
|
|
1688
|
-
* previously paused review request. The tool returns the
|
|
1689
|
-
* reviewer's verdict instead of throwing again.
|
|
1690
|
-
*/
|
|
1691
|
-
declare function createRequestReviewTool(sessionId: string, hitlResume?: AgentRunParams["hitlResume"]): AgentTool<typeof reviewSchema, ReviewResult>;
|
|
1692
|
-
//#endregion
|
|
1693
1622
|
//#region src/tools/ui-tool.d.ts
|
|
1694
1623
|
type UiToolOptions = {
|
|
1695
1624
|
/** Unique tool name (must be valid identifier, e.g. "collect_feedback"). */name: string; /** Human-readable label shown in tool listings. */
|
|
@@ -2219,6 +2148,7 @@ declare const HITL_MESSAGES: {
|
|
|
2219
2148
|
};
|
|
2220
2149
|
};
|
|
2221
2150
|
declare function approvalSummaryFromResolution(resolution: HitlResolution): string;
|
|
2151
|
+
declare function formatApprovalResolution(resolution: HitlResolution): string;
|
|
2222
2152
|
/**
|
|
2223
2153
|
* Formats a clarify resolution into a JSON string suitable for the tool
|
|
2224
2154
|
* result content in the transcript. The model sees this as the clarify
|
|
@@ -2233,4 +2163,4 @@ declare function formatClarifyResolution(resolution: HitlResolution): string;
|
|
|
2233
2163
|
declare function formatReviewResolution(resolution: HitlResolution): string;
|
|
2234
2164
|
declare function buildResumeNarration(resolution: HitlResolution, kind: string): string;
|
|
2235
2165
|
//#endregion
|
|
2236
|
-
export { AgentBinding, AgentConfig, type AgentCustomProgressEvent, AgentModelConfig, type AgentProgressEvent, type AgentRunParams, type AgentRunResult, AgentsConfig, BOOTSTRAP_FILE_NAMES, BOOTSTRAP_MAX_CHARS, BOOTSTRAP_TOTAL_MAX_CHARS, type BootstrapContextFile, type BootstrapEnsureResult, type BootstrapFile, type BootstrapMountResult, type BootstrapMountStatus, type CallbackEventPayload, type CallbackPayload, type Channel, type ContextManager, DEFAULT_SESSION_STORE_NAME, type EmbeddingProvider, type EmbeddingProviderContext, type EmbeddingProviderFactory, type EmbeddingProviderRegistration, HITL_MESSAGES, type HitlPauseContext, HitlPauseSignal, type HitlToolContext, MAX_CHILDREN_PER_SESSION, MAX_SUBAGENT_DEPTH, type MemoryCallOptions, type MemoryChangeSource, type MemoryChangedEvent, type MemoryChangedHandler, MemoryIndexManager, type MemoryProvider, type MemoryProviderContext, type MemoryProviderFactory, type MemoryProviderRegistration, type MemoryProviderStatus, type MemorySearchOptions, type MemorySearchResult, type NormalizedPluginsConfig, PLUGIN_MANIFEST_FILENAME, PLUGIN_MANIFEST_FILENAMES, type PersistedSubagentRunRecord, type PersistedToolResult, type PluginApi, type PluginCandidate, type PluginConfigUiHint, type PluginCustomProgressInput, type PluginDiagnostic, type PluginDiscoveryOptions, type PluginDiscoveryResult, type PluginEntryConfig, type PluginExecutionRuntime, type PluginHookAfterCompactionEvent, type PluginHookAfterPromptBuildEvent, type PluginHookAfterToolCallEvent, type PluginHookAgentContext, type PluginHookAgentEndEvent, type PluginHookAssistantMessageEndEvent, type PluginHookBeforeCompactionEvent, type PluginHookBeforeModelResolveEvent, type PluginHookBeforeModelResolveResult, type PluginHookBeforePromptBuildEvent, type PluginHookBeforePromptBuildResult, type PluginHookBeforeToolCallEvent, type PluginHookBeforeToolCallResult, type PluginHookHandlerMap, type PluginHookLlmInputEvent, type PluginHookLlmOutputEvent, type PluginHookMemoryChangedEvent, type PluginHookName, PluginHookRegistry, type PluginHookSessionEndEvent, type PluginHookSessionResetEvent, type PluginHookSessionStartEvent, type PluginKind, type PluginManifest, type PluginManifestLoadResult, type PluginManifestRegistry, type PluginOrigin, type PluginProgressEmitter, type PluginRecord, type PluginRegistry, type PluginRuntime, type PluginRuntimeContext, type PluginSystem, type PluginSystemOptions, type PluginToolOptions, PluginToolRegistry, type PluginUiToolDescriptor, type PluginUiToolOptions, type PluginsConfig, type PluginsConfigValidationResult, type RegisteredPluginTool, type ResumeOptions, type ResumeValidationResult, type RunResultPayload, type SessionContextStore, type SessionExport, type SessionInspection, type SessionMetadata, type SessionMetadataUpdate, type SessionSummary, type Skill, type SlashCommandList, type SubagentContext, SubagentRegistry, type SubagentRunRecord, type SubagentStatus, type SubagentToolsContext, type SystemPromptParams, type ToolLoopDetectionConfig, type TranscriptEntry, type UiToolInputSchema, type UiToolOptions, UiToolPauseSignal, addAgent, addBinding, aimaxDir, appendToMemory, appendTranscriptEntry, approvalSummaryFromResolution, bootstrapMountLayout, buildBootstrapContextFiles, buildResumeNarration, buildSkillsPrompt, buildSubagentAnnounceMessage, buildSystemPrompt, cleanupOldSubagentRecords, clearPendingHitl, clearPendingUiTool, collapseLogPath, contextSnapshotPath, createAgentTools, createApplyPatchTool, createBashTool, createBuiltinMemoryProvider,
|
|
2166
|
+
export { AgentBinding, AgentConfig, type AgentCustomProgressEvent, AgentModelConfig, type AgentProgressEvent, type AgentRunParams, type AgentRunResult, AgentsConfig, BOOTSTRAP_FILE_NAMES, BOOTSTRAP_MAX_CHARS, BOOTSTRAP_TOTAL_MAX_CHARS, type BootstrapContextFile, type BootstrapEnsureResult, type BootstrapFile, type BootstrapMountResult, type BootstrapMountStatus, type CallbackEventPayload, type CallbackPayload, type Channel, type ContextManager, DEFAULT_SESSION_STORE_NAME, type EmbeddingProvider, type EmbeddingProviderContext, type EmbeddingProviderFactory, type EmbeddingProviderRegistration, HITL_MESSAGES, type HitlPauseContext, HitlPauseSignal, type HitlToolContext, MAX_CHILDREN_PER_SESSION, MAX_SUBAGENT_DEPTH, type MemoryCallOptions, type MemoryChangeSource, type MemoryChangedEvent, type MemoryChangedHandler, MemoryIndexManager, type MemoryProvider, type MemoryProviderContext, type MemoryProviderFactory, type MemoryProviderRegistration, type MemoryProviderStatus, type MemorySearchOptions, type MemorySearchResult, type NormalizedPluginsConfig, PLUGIN_MANIFEST_FILENAME, PLUGIN_MANIFEST_FILENAMES, type PersistedSubagentRunRecord, type PersistedToolResult, type PluginApi, type PluginCandidate, type PluginConfigUiHint, type PluginCustomProgressInput, type PluginDiagnostic, type PluginDiscoveryOptions, type PluginDiscoveryResult, type PluginEntryConfig, type PluginExecutionRuntime, type PluginHookAfterCompactionEvent, type PluginHookAfterPromptBuildEvent, type PluginHookAfterToolCallEvent, type PluginHookAgentContext, type PluginHookAgentEndEvent, type PluginHookAssistantMessageEndEvent, type PluginHookBeforeCompactionEvent, type PluginHookBeforeModelResolveEvent, type PluginHookBeforeModelResolveResult, type PluginHookBeforePromptBuildEvent, type PluginHookBeforePromptBuildResult, type PluginHookBeforeToolCallEvent, type PluginHookBeforeToolCallResult, type PluginHookHandlerMap, type PluginHookLlmInputEvent, type PluginHookLlmOutputEvent, type PluginHookMemoryChangedEvent, type PluginHookName, PluginHookRegistry, type PluginHookSessionEndEvent, type PluginHookSessionResetEvent, type PluginHookSessionStartEvent, type PluginKind, type PluginManifest, type PluginManifestLoadResult, type PluginManifestRegistry, type PluginOrigin, type PluginProgressEmitter, type PluginRecord, type PluginRegistry, type PluginRuntime, type PluginRuntimeContext, type PluginSystem, type PluginSystemOptions, type PluginToolOptions, PluginToolRegistry, type PluginUiToolDescriptor, type PluginUiToolOptions, type PluginsConfig, type PluginsConfigValidationResult, type RegisteredPluginTool, type ResumeOptions, type ResumeValidationResult, type RunResultPayload, type SessionContextStore, type SessionExport, type SessionInspection, type SessionMetadata, type SessionMetadataUpdate, type SessionSummary, type Skill, type SlashCommandList, type SubagentContext, SubagentRegistry, type SubagentRunRecord, type SubagentStatus, type SubagentToolsContext, type SystemPromptParams, type ToolLoopDetectionConfig, type TranscriptEntry, type UiToolInputSchema, type UiToolOptions, UiToolPauseSignal, addAgent, addBinding, aimaxDir, appendToMemory, appendTranscriptEntry, approvalSummaryFromResolution, bootstrapMountLayout, buildBootstrapContextFiles, buildResumeNarration, buildSkillsPrompt, buildSubagentAnnounceMessage, buildSystemPrompt, cleanupOldSubagentRecords, clearPendingHitl, clearPendingUiTool, collapseLogPath, contextSnapshotPath, createAgentTools, createApplyPatchTool, createBashTool, createBuiltinMemoryProvider, createContextManager, createEditFileTool, createExecTool, createImageTool, createListDirTool, createMemoryAppendTool, createMemoryGetTool, createMemorySearchTool, createPendingHitl, createPendingUiTool, createPluginProgressEmitter, createPluginRuntime, createProcessTool, createReadFileTool, createSession, createSessionContextStore, createSessionsSpawnTool, createSubagentsTool, createUiTool, createWriteFileTool, defaultUiToolInputSchema, deleteMemoryFile, discoverAIMaxPlugins, ensureBootstrapMountLayout, ensureSession, exportSession, formatApprovalResolution, formatClarifyResolution, formatReviewResolution, generateSessionTitle, getAgentConfig, getMemoryLines, hasBootstrapSentinel, hitlHistoryPath, initializePluginSystem, inspectBootstrapMountLayout, inspectSession, isBootstrapMountLayoutReady, isHitlPauseSignal, isUiToolPauseSignal, listAgents, listAvailableSlashCommands, listBindings, listMemoryFiles, listSessionSummaries, listSessions, listSubagentRunsFromDisk, loadAgentsConfig, loadBootstrapFiles, readPendingHitl as loadPendingHitl, readPendingHitl, readPendingUiTool as loadPendingUiTool, readPendingUiTool, loadPluginManifest, loadPluginManifestRegistry, loadPlugins, loadSessionContextSnapshot, loadSessionMetadata, loadSkills, loadSkillsFromDirs, loadSkillsWithPluginDirs, loadSubagentRegistryFromDisk, loadTranscript, memoryDir, metadataPath, normalizeAgentId, normalizePluginsConfig, normalizeSessionStoreName, pendingHitlPath, pendingUiToolPath, primaryMemoryPath, readHitlHistory, readMemoryFile, readPrimaryMemory, registerEmbeddingProvider, registerMemoryProvider, removeAgent, removeBindings, replaceMemoryFile, resetEmbeddingProviderRegistryForTests, resetMemoryProviderRegistryForTests, resolveAgentDir, resolveAgentIdByBinding, resolveAgentsConfigPath, resolveDefaultAgentId, resolveEmbeddingProvider, resolveHitlRequest, resolveHitlRequest as resolvePendingHitl, resolveMemoryProvider, resolveModelFallbacks, resolveModelString, resolvePendingUiTool, resolvePluginManifestPath, rewriteTranscript, runAgent, saveAgentsConfig, saveSessionMetadata, saveSubagentRegistryToDisk, searchMemory, sessionDir, sessionMemoryPath, sessionsDir, skillsDir, toolResultsDir, transcriptPath, transitionHitlStatus, updateAgentIdentity, updateSessionMetadata, validatePluginsConfig, validateResume, wrapToolsWithHooks };
|