@gencode/agents 0.0.54 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/README.md +72 -0
- package/dist/{builtin-provider-C72KTRcP.js → builtin-provider-BDSbl8Dg.js} +11 -11
- package/dist/index.d.ts +75 -45
- package/dist/index.js +61 -75
- package/package.json +4 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# @gencode/agents
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 6a154b5: Remove HEARTBEAT feature from @gencode/agents. Heartbeat is not applicable to the current architecture, so all related template, bootstrap file loading, system prompt section, and test references have been removed.
|
|
8
|
+
- 71b3e30: Add stable session metadata types to @gencode/shared, expand memory tool suite, and switch subagent spawn to synchronous result delivery.
|
|
9
|
+
|
|
10
|
+
- @gencode/shared: export `SessionSummary` and `SessionMetadata` types for cross-package use
|
|
11
|
+
- @gencode/agents: add memory_write, memory_log, memory_list, memory_forget, memory_update tools; improve memory tool descriptions and system prompt guidance; change subagent spawn from async acceptance to synchronous result return; suppress redundant assistant text after subagent completion
|
|
12
|
+
- @gencode/cli: update memory tool test coverage to match new tools
|
|
13
|
+
|
|
14
|
+
### Patch Changes
|
|
15
|
+
|
|
16
|
+
- 8ef3f8f: Add `sessionExists` helper to check if a session directory exists, and use it in runner to correctly detect new sessions when the requested session ID does not exist on disk
|
|
17
|
+
- 839f628: Load preset system prompt from `/aimax/system_prompt.md` instead of hardcoding the identity line in builder
|
|
18
|
+
- 350b9d1: Add a publish-time changelog guard and include package changelogs in npm artifacts.
|
|
19
|
+
- a2149e3: Remove the Documentation section (`buildDocsSection`) from the agent system prompt and clean up the `docs` parameter from types, builder, runtime, and subagent tooling
|
|
20
|
+
- 5f15359: Rename tool `sessions_spawn` to `subagent_spawn` and strengthen description to explicitly require usage when user mentions subagent
|
|
21
|
+
- Updated dependencies [350b9d1]
|
|
22
|
+
- Updated dependencies [71b3e30]
|
|
23
|
+
- @gencode/shared@0.1.0
|
|
24
|
+
|
|
25
|
+
## 0.0.54
|
|
26
|
+
|
|
27
|
+
### Patch Changes
|
|
28
|
+
|
|
29
|
+
- Establish the initial changelog baseline for the current published package version.
|
|
30
|
+
- Fix `subagent_spawn` transcript persistence so subagent completion is returned as the original tool result instead of adding extra assistant messages.
|
package/README.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# @gencode/agents
|
|
2
|
+
|
|
3
|
+
## 包定位
|
|
4
|
+
|
|
5
|
+
`@gencode/agents` 是 AIMax 的 agent 核心领域层。
|
|
6
|
+
它应成为 agent 执行流程、session 相关领域能力以及内部运行期事件的主要归属位置。
|
|
7
|
+
|
|
8
|
+
## 负责内容
|
|
9
|
+
|
|
10
|
+
这个包适合承载:
|
|
11
|
+
- agent 执行流程
|
|
12
|
+
- session 领域行为
|
|
13
|
+
- memory / bootstrap / identity 相关领域能力
|
|
14
|
+
- 内部运行期协调
|
|
15
|
+
- 结构化内部事件产出
|
|
16
|
+
- 不依赖外部传输层的 agent 核心抽象
|
|
17
|
+
|
|
18
|
+
## 不负责内容
|
|
19
|
+
|
|
20
|
+
这个包不应直接承担以下进程外通信职责:
|
|
21
|
+
- stdout 渲染
|
|
22
|
+
- HTTP callback 投递
|
|
23
|
+
- websocket 传输投递
|
|
24
|
+
- Web 服务侧逻辑
|
|
25
|
+
- CLI 参数解析
|
|
26
|
+
|
|
27
|
+
这些职责属于 `@gencode/cli` 或更高层的集成包。
|
|
28
|
+
|
|
29
|
+
## 当前源码入口
|
|
30
|
+
|
|
31
|
+
阅读本包时,建议先看:
|
|
32
|
+
- `src/index.ts` —— 主入口
|
|
33
|
+
- `src/types.ts` —— 包内类型定义
|
|
34
|
+
- `src/build-config.test.ts` —— 当前包级验证示例
|
|
35
|
+
|
|
36
|
+
当 `dist/` 存在时,应将其视为构建产物,而不是主要编辑目标。
|
|
37
|
+
优先阅读源码与测试。
|
|
38
|
+
|
|
39
|
+
## 与其他包的关系
|
|
40
|
+
|
|
41
|
+
- `@gencode/cli` 使用本包执行 agent 行为,并把内部事件适配为外部输出
|
|
42
|
+
- `@gencode/shared` 应承载稳定的跨包协议,而不是在本包内重复定义
|
|
43
|
+
- `@gencode/web` 不允许绕过 CLI 直接消费本包
|
|
44
|
+
|
|
45
|
+
## 开发说明
|
|
46
|
+
|
|
47
|
+
当你在这里增加新能力时:
|
|
48
|
+
- 保持职责在领域侧,而不是传输侧
|
|
49
|
+
- 优先返回显式接口与结构化输出
|
|
50
|
+
- 不要把 callback / websocket 认知嵌入 agent 内核
|
|
51
|
+
- 当一个对外结构开始被多个包复用时,应优先沉淀到 `@gencode/shared`
|
|
52
|
+
|
|
53
|
+
## 验证
|
|
54
|
+
|
|
55
|
+
在工作区根目录可运行:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
pnpm -C source/packages/agents test
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
类型检查通常通过工作区命令统一运行:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
pnpm -C source typecheck
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## 相关规格文档
|
|
68
|
+
|
|
69
|
+
- `../../../specs/system-overview.md`
|
|
70
|
+
- `../../../specs/architecture-boundaries.md`
|
|
71
|
+
- `../../../specs/development-workflow.md`
|
|
72
|
+
- `../../../specs/repo-map.md`
|
|
@@ -3,9 +3,9 @@ import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{createRequire as t}fro
|
|
|
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 ne(e,t,i,a){await y(e,t,a);let o=d(e,t,a),s=i(await b(e,t,a)),l=s.map(e=>JSON.stringify(e)).join(`
|
|
4
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 re(e,t,r,i){await y(e,t,i);let a=_(e,t,i),o=JSON.stringify(r)+`
|
|
5
5
|
`;await n.appendFile(a,o,`utf-8`)}async function ie(e,t,r){let i=_(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(`
|
|
6
|
-
`)){let t=e.trim();if(t)try{o.push(JSON.parse(t))}catch{}}return o}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 y(e,t.id,r);let i=f(e,t.id,r);await n.writeFile(i,JSON.stringify(t,null,2),`utf-8`)}async function ae(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 oe(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?v:{version:2,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:v.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 v;throw e}}async function T(e,t,n){let[r,i,a]=await Promise.all([C(e,t,n),b(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
|
|
6
|
+
`)){let t=e.trim();if(t)try{o.push(JSON.parse(t))}catch{}}return o}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 y(e,t.id,r);let i=f(e,t.id,r);await n.writeFile(i,JSON.stringify(t,null,2),`utf-8`)}async function ae(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 oe(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?v:{version:2,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:v.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 v;throw e}}async function se(e,t,r){let i=u(e,t,r);try{return(await n.stat(i)).isDirectory()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function T(e,t,n){let[r,i,a]=await Promise.all([C(e,t,n),b(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 ce(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 le(e){try{o.mkdirSync(e,{recursive:!0})}catch{}return e}function ue(e){return e.trim().replace(/^[./]+/,``).replace(/\\/g,`/`)}function de(e){let t=ue(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 fe(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 pe(e,t){let n=e.split(`
|
|
7
7
|
`);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(`
|
|
8
|
-
`),r=e.lineNo,i=t.lineNo;a.push({startLine:r,endLine:i,text:n,hash:
|
|
8
|
+
`),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 me(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 he(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 ge(e){return(e.toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[]).filter(Boolean)}function _e(e){return i.createHash(`sha256`).update(e).digest().readUInt32BE(0)}function M(e,t=384){let n=Array(t).fill(0),r=ge(e);if(r.length===0)return n;for(let e of r){let r=_e(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 ve(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 ye(){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 be(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 xe(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=be(i,n.get(e.id)??L(e.content));t>r&&(r=t)}return r}function Se(e,t,n){return n*e-(1-n)*t}function Ce(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=Se(l(n.score),xe(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 we(e,t={}){if(e.length===0)return e;let n=new Map;return Ce(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 R={enabled:!1,halfLifeDays:30},z=/(?:^|\/)(?:memory)\/(\d{4})-(\d{2})-(\d{2})\.md$/;function Te(e){return!Number.isFinite(e)||e<=0?0:Math.LN2/e}function Ee(e){let t=Te(e.halfLifeDays),n=Math.max(0,e.ageInDays);return t<=0||!Number.isFinite(n)?1:Math.exp(-t*n)}function De(e){return e.score*Ee(e)}function Oe(e){let t=e.replaceAll(`\\`,`/`).replace(/^\.\//,``),n=z.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 ke(e){let t=e.replaceAll(`\\`,`/`).replace(/^\.\//,``);return t===`MEMORY.md`||t===`memory.md`?!0:t.startsWith(`memory/`)?!z.test(t):!1}async function Ae(e){let t=Oe(e.filePath);if(t)return t;if(e.source===`memory`&&ke(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 je(e,t){return Math.max(0,t-e.getTime())/864e5}async function Me(e){let t={...R,...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=Ae({filePath:i.path,source:i.source,memoryRoot:e.memoryRoot}),r.set(a,o));let s=await o;if(!s)return i;let c=De({score:i.score,ageInDays:je(s,n),halfLifeDays:t.halfLifeDays});return{...i,score:c}}))}function Ne(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 Pe(e){return 1/(1+(Number.isFinite(e)?Math.max(0,e):999))}async function Fe(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 Me({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:{...R,...e.temporalDecay},memoryRoot:e.memoryRoot,nowMs:e.nowMs})).slice().sort((e,t)=>t.score-e.score),r={...I,...e.mmr};return r.enabled?we(n,r):n}function Ie(e){e.db.exec(`
|
|
9
9
|
CREATE TABLE IF NOT EXISTS meta (
|
|
10
10
|
key TEXT PRIMARY KEY,
|
|
11
11
|
value TEXT NOT NULL
|
|
@@ -42,18 +42,18 @@ import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{createRequire as t}fro
|
|
|
42
42
|
updated_at INTEGER NOT NULL,
|
|
43
43
|
PRIMARY KEY (provider, model, provider_key, hash)
|
|
44
44
|
);
|
|
45
|
-
`),e.db.exec(`CREATE INDEX IF NOT EXISTS idx_embedding_cache_updated_at ON ${e.embeddingCacheTable}(updated_at);`);let t=!1,n;if(e.ftsEnabled)try{e.db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.ftsTable} USING fts5(\n text,\n id UNINDEXED,\n path UNINDEXED,\n source UNINDEXED,\n model UNINDEXED,\n start_line UNINDEXED,\n end_line UNINDEXED\n);`),t=!0}catch(e){let r=e instanceof Error?e.message:String(e);t=!1,n=r}return
|
|
45
|
+
`),e.db.exec(`CREATE INDEX IF NOT EXISTS idx_embedding_cache_updated_at ON ${e.embeddingCacheTable}(updated_at);`);let t=!1,n;if(e.ftsEnabled)try{e.db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.ftsTable} USING fts5(\n text,\n id UNINDEXED,\n path UNINDEXED,\n source UNINDEXED,\n model UNINDEXED,\n start_line UNINDEXED,\n end_line UNINDEXED\n);`),t=!0}catch(e){let r=e instanceof Error?e.message:String(e);t=!1,n=r}return B(e.db,`files`,`source`,`TEXT NOT NULL DEFAULT 'memory'`),B(e.db,`chunks`,`source`,`TEXT NOT NULL DEFAULT 'memory'`),e.db.exec(`CREATE INDEX IF NOT EXISTS idx_chunks_path ON chunks(path);`),e.db.exec(`CREATE INDEX IF NOT EXISTS idx_chunks_source ON chunks(source);`),{ftsAvailable:t,...n?{ftsError:n}:{}}}function B(e,t,n,r){e.prepare(`PRAGMA table_info(${t})`).all().some(e=>e.name===n)||e.exec(`ALTER TABLE ${t} ADD COLUMN ${n} ${r}`)}function V(e,t){return e.length<=t?e:e.slice(0,t)}const Le=e=>Buffer.from(new Float32Array(e).buffer);async function Re(e){return e.queryVec.length===0||e.limit<=0?[]:await e.ensureVectorReady(e.queryVec.length)?e.db.prepare(`SELECT c.id, c.path, c.start_line, c.end_line, c.text,
|
|
46
46
|
c.source,
|
|
47
47
|
vec_distance_cosine(v.embedding, ?) AS dist
|
|
48
|
-
FROM ${e.vectorTable} v\n JOIN chunks c ON c.id = v.id\n WHERE c.model = ?${e.sourceFilterVec.sql}\n ORDER BY dist ASC\n LIMIT ?`).all(
|
|
48
|
+
FROM ${e.vectorTable} v\n JOIN chunks c ON c.id = v.id\n WHERE c.model = ?${e.sourceFilterVec.sql}\n ORDER BY dist ASC\n LIMIT ?`).all(Le(e.queryVec),e.providerModel,...e.sourceFilterVec.params,e.limit).map(t=>({id:t.id,path:t.path,startLine:t.start_line,endLine:t.end_line,score:1-t.dist,snippet:V(t.text,e.snippetMaxChars),source:t.source})):ze({db:e.db,providerModel:e.providerModel,sourceFilter:e.sourceFilterChunks}).map(t=>({chunk:t,score:he(e.queryVec,t.embedding)})).filter(e=>Number.isFinite(e.score)).slice().sort((e,t)=>t.score-e.score).slice(0,e.limit).map(t=>({id:t.chunk.id,path:t.chunk.path,startLine:t.chunk.startLine,endLine:t.chunk.endLine,score:t.score,snippet:V(t.chunk.text,e.snippetMaxChars),source:t.chunk.source}))}function ze(e){return e.db.prepare(`SELECT id, path, start_line, end_line, text, embedding, source
|
|
49
49
|
FROM chunks
|
|
50
|
-
WHERE model = ?${e.sourceFilter.sql}`).all(e.providerModel,...e.sourceFilter.params).map(e=>({id:e.id,path:e.path,startLine:e.start_line,endLine:e.end_line,text:e.text,embedding:j(e.embedding),source:e.source}))}async function
|
|
51
|
-
`);for(let e=0;e<u.length;e+=1){let t=u[e]?.trim();if(t)try{let n=JSON.parse(t),r=n.role??`unknown`,i=
|
|
50
|
+
WHERE model = ?${e.sourceFilter.sql}`).all(e.providerModel,...e.sourceFilter.params).map(e=>({id:e.id,path:e.path,startLine:e.start_line,endLine:e.end_line,text:e.text,embedding:j(e.embedding),source:e.source}))}async function Be(e){if(e.limit<=0)return[];let t=e.buildFtsQuery(e.query);if(!t)return[];let n=e.providerModel?` AND model = ?`:``,r=e.providerModel?[e.providerModel]:[];return e.db.prepare(`SELECT id, path, source, start_line, end_line, text,\n bm25(${e.ftsTable}) AS rank\n FROM ${e.ftsTable}\n WHERE ${e.ftsTable} MATCH ?${n}${e.sourceFilter.sql}\n ORDER BY rank ASC\n LIMIT ?`).all(t,...r,...e.sourceFilter.params,e.limit).map(t=>{let n=e.bm25RankToScore(t.rank);return{id:t.id,path:t.path,startLine:t.start_line,endLine:t.end_line,score:n,textScore:n,snippet:V(t.text,e.snippetMaxChars),source:t.source}})}const Ve=t(import.meta.url);function He(){try{return Ve(`node:sqlite`)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`SQLite support is unavailable in this Node runtime (missing node:sqlite). ${t}`,{cause:e})}}const H={chunkTokens:400,chunkOverlap:80,maxResults:6,minScore:.35,embedding:{},experimental:{sessionMemory:!1},sources:[`memory`],store:{sessionStoreName:void 0,vector:{enabled:!0}},hybrid:{enabled:!0,vectorWeight:.7,textWeight:.3,candidateMultiplier:4,mmr:{enabled:!1,lambda:.7},temporalDecay:{enabled:!1,halfLifeDays:30}},cache:{enabled:!0,maxEntries:5e4},sync:{onSessionStart:!0,onSearch:!0,watch:!0,watchDebounceMs:1500,sessions:{deltaBytes:1e5,deltaMessages:50}},citations:`auto`};async function Ue(e){try{let t=await import(`sqlite-vec`),n=e.extensionPath?.trim()?e.extensionPath.trim():void 0,r=n??t.getLoadablePath();return e.db.enableLoadExtension(!0),n?e.db.loadExtension(r):t.load(e.db),{ok:!0,extensionPath:r}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function We(e,t,n){let i=l(e,{storeName:n});return r.relative(i,t).replace(/\\/g,`/`)}async function U(e,t){let i=l(e,{storeName:t});try{let e=await n.readdir(i,{withFileTypes:!0}),t=[];for(let a of e){if(!a.isDirectory())continue;let e=r.join(i,a.name,`transcript.jsonl`);try{(await n.stat(e)).isFile()&&t.push(e)}catch{}}return t}catch(e){if(D(e))return[];throw e}}function Ge(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e==`string`?e:e&&typeof e==`object`&&`text`in e?String(e.text??``):``).filter(Boolean).join(` `):e?String(e):``}async function Ke(e,t,i){let a;try{a=await n.stat(t)}catch(e){if(D(e))return null;throw e}let o;try{o=await n.readFile(t,`utf-8`)}catch(e){if(D(e))return null;throw e}let s=[],l=[],u=o.split(`
|
|
51
|
+
`);for(let e=0;e<u.length;e+=1){let t=u[e]?.trim();if(t)try{let n=JSON.parse(t),r=n.role??`unknown`,i=Ge(n.content);if(!i)continue;let a=i.split(`
|
|
52
52
|
`);for(let t of a)s.push(`[${r}] ${t}`),l.push(e+1)}catch{}}let d=s.join(`
|
|
53
|
-
`),f=
|
|
53
|
+
`),f=A(d);return{path:r.join(c(i),We(e,t,i)).replace(/\\/g,`/`),absPath:t,mtimeMs:a.mtimeMs,size:a.size,hash:f,content:d,lineMap:l}}const W=`chunks_vec`,G=`chunks_fts`,K=`embedding_cache`,q=`memory_index_meta_v1`,J=3e4,Y=new Map;function X(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 Z=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;sessionDeltas=new Map;static get(t,n){let i=r.join(t,`.aimax`),a=X(H,n),o=`${i}::${c(a.store.sessionStoreName)}`,s=Y.get(o);if(s)return n&&s.applyConfig(n),s;let l=new e(t,i,a);return Y.set(o,l),l}constructor(e,t,n){this.dataDir=e,this.memoryRoot=t,this.storePath=r.join(t,`.index.sqlite`),this.config=X(H,n),this.sessionStoreName=c(this.config.store.sessionStoreName),this.provider=N(),this.providerKey=this.computeProviderKey(),this.applyEmbeddingProvider(),this.vector.enabled=this.config.store.vector.enabled,this.vector.extensionPath=this.config.store.vector.extensionPath,this.db=this.openDatabase(),this.ensureSchema(),this.ensureWatcher(),this.ensureSessionListener(),this.dirty=!0}applyConfig(e){this.config=X(this.config,e),this.sessionStoreName=c(this.config.store.sessionStoreName),this.applyEmbeddingProvider(),this.vector.enabled=this.config.store.vector.enabled,this.vector.extensionPath=this.config.store.vector.extensionPath,this.ensureWatcher(),this.ensureSessionListener()}warmSession(){this.config.sync.onSessionStart&&this.sync({reason:`session-start`}).catch(()=>{})}noteSessionUpdate(e){this.scheduleSessionDirty(e)}status(){let e=this.buildSourceFilter(),t=this.db.prepare(`SELECT COUNT(*) as c FROM files WHERE 1=1${e.sql}`).get(...e.params),n=this.db.prepare(`SELECT COUNT(*) as c FROM chunks WHERE 1=1${e.sql}`).get(...e.params),r=(()=>{let t=Array.from(this.config.sources);if(t.length===0)return[];let n=new Map;for(let e of t)n.set(e,{files:0,chunks:0});let r=this.db.prepare(`SELECT source, COUNT(*) as c FROM files WHERE 1=1${e.sql} GROUP BY source`).all(...e.params);for(let e of r){let t=n.get(e.source)??{files:0,chunks:0};t.files=e.c??0,n.set(e.source,t)}let i=this.db.prepare(`SELECT source, COUNT(*) as c FROM chunks WHERE 1=1${e.sql} GROUP BY source`).all(...e.params);for(let e of i){let t=n.get(e.source)??{files:0,chunks:0};t.chunks=e.c??0,n.set(e.source,t)}return t.map(e=>Object.assign({source:e},n.get(e)))})(),i=this.provider?`hybrid`:`fts-only`,a=this.config.cache.enabled?this.db.prepare(`SELECT COUNT(*) as c FROM ${K}`).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},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}}}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[];this.readMeta()?this.config.sync.onSearch&&(this.dirty||this.sessionsDirty)&&this.sync({reason:`search`}).catch(()=>{}):await this.sync({reason:`boot`});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),o=a.some(e=>e!==0)?await this.searchVector(a,r).catch(()=>[]):[];if(!n.enabled||!this.ftsAvailable)return o.filter(e=>e.score>=this.config.minScore).slice(0,this.config.maxResults);let s=await Fe({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}),c=s.filter(e=>e.score>=this.config.minScore);if(c.length>0||i.length===0)return this.decorateCitations(c.slice(0,this.config.maxResults));let l=Math.min(this.config.minScore,n.textWeight),u=s.filter(e=>e.score>=l).slice(0,this.config.maxResults);return this.decorateCitations(u)}async readFile(e){let{absPath:t,relPath:r}=this.resolveMemoryFilePath(e.relPath);if((await ce(t)).missing)return{text:``,path:r};let i;try{i=await n.readFile(t,`utf-8`)}catch(e){if(D(e))return{text:``,path:r};throw e}if(!e.from&&!e.lines)return{text:i,path:r};let a=i.split(`
|
|
54
54
|
`),o=Math.max(1,e.from??1),s=Math.max(1,e.lines??a.length);return{text:a.slice(o-1,o-1+s).join(`
|
|
55
|
-
`),path:r}}async replaceFile(e){let{absPath:t}=this.resolveMemoryFilePath(e.relPath);await n.mkdir(r.dirname(t),{recursive:!0}),await n.writeFile(t,e.content,`utf-8`),this.dirty=!0}async deleteFile(e){let{absPath:t}=this.resolveMemoryFilePath(e);try{await n.unlink(t)}catch(e){if(
|
|
56
|
-
`)?e:`${e}\n`;await n.appendFile(i,a,`utf-8`),this.dirty=!0}openDatabase(){le(r.dirname(this.storePath));let{DatabaseSync:e}=
|
|
55
|
+
`),path:r}}async replaceFile(e){let{absPath:t}=this.resolveMemoryFilePath(e.relPath);await n.mkdir(r.dirname(t),{recursive:!0}),await n.writeFile(t,e.content,`utf-8`),this.dirty=!0}async deleteFile(e){let{absPath:t}=this.resolveMemoryFilePath(e);try{await n.unlink(t)}catch(e){if(D(e))return;throw e}this.dirty=!0}async appendToMemory(e){let t=this.memoryRoot;await n.mkdir(t,{recursive:!0});let i=r.join(t,`MEMORY.md`),a=e.endsWith(`
|
|
56
|
+
`)?e:`${e}\n`;await n.appendFile(i,a,`utf-8`),this.dirty=!0}openDatabase(){le(r.dirname(this.storePath));let{DatabaseSync:e}=He();return new e(this.storePath,{allowExtension:this.vector.enabled})}ensureSchema(){let e=Ie({db:this.db,embeddingCacheTable:K,ftsTable:G,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(),J,`sqlite-vec load timed out after ${Math.round(J/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 Ue({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 ${W} 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 ${W}`)}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=[r.join(this.memoryRoot,`MEMORY.md`),r.join(this.memoryRoot,`memory.md`),r.join(this.memoryRoot,`memory`)],t=()=>{this.dirty=!0,this.scheduleWatchSync()};for(let n of e)try{let e=o.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=l(this.dataDir,{storeName:this.sessionStoreName});try{let t=o.watch(e,{recursive:!0},(t,n)=>{if(!n||!n.endsWith(`transcript.jsonl`))return;let i=r.join(e,n);this.scheduleSessionDirty(i)});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 r;try{r=await n.stat(e)}catch{return null}let i=r.size,a=this.sessionDeltas.get(e);a||(a={lastSize:0,pendingBytes:0,pendingMessages:0},this.sessionDeltas.set(e,a));let o=Math.max(0,i-a.lastSize);return o===0&&i===a.lastSize?{deltaBytes:t.deltaBytes,deltaMessages:t.deltaMessages,pendingBytes:a.pendingBytes,pendingMessages:a.pendingMessages}:(i<a.lastSize?(a.lastSize=i,a.pendingBytes+=i,t.deltaMessages>0&&(t.deltaBytes<=0||a.pendingBytes<t.deltaBytes)&&(a.pendingMessages+=await this.countNewlines(e,0,i))):(a.pendingBytes+=o,t.deltaMessages>0&&(t.deltaBytes<=0||a.pendingBytes<t.deltaBytes)&&(a.pendingMessages+=await this.countNewlines(e,a.lastSize,i)),a.lastSize=i),this.sessionDeltas.set(e,a),{deltaBytes:t.deltaBytes,deltaMessages:t.deltaMessages,pendingBytes:a.pendingBytes,pendingMessages:a.pendingMessages})}async countNewlines(e,t,r){if(r<=t)return 0;let i;try{i=await n.open(e,`r`)}catch{return 0}try{let e=t,n=0,a=Buffer.alloc(64*1024);for(;e<r;){let t=Math.min(a.length,r-e),{bytesRead:o}=await i.read(a,0,t,e);if(o<=0)break;for(let e=0;e<o;e+=1)a[e]===10&&(n+=1);e+=o}return n}finally{await i.close()}}computeProviderKey(){return A(JSON.stringify({provider:this.provider.id,model:this.provider.model}))}resolveMemoryFilePath(e){let t=e.trim();if(!t)throw Error(`path required`);let n=r.isAbsolute(t)?r.resolve(t):r.resolve(this.memoryRoot,t),i=r.relative(this.memoryRoot,n).replace(/\\/g,`/`);if(!(i.length>0&&!i.startsWith(`..`)&&!r.isAbsolute(i)&&de(i))||!n.endsWith(`.md`))throw Error(`path required`);return{absPath:n,relPath:i}}applyEmbeddingProvider(){let e=this.config.embedding?.providerId?.trim();if(e){let t=F({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=N(),this.embeddingProviderId=void 0,this.providerKey=this.computeProviderKey(),this.dirty=!0)}readMeta(){let e=this.db.prepare(`SELECT value FROM meta WHERE key = ?`).get(q);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(q,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 ${K}\n WHERE provider = ? AND model = ? AND provider_key = ? AND hash IN (${a})`).all(...r,...i);for(let e of o)n.set(e.hash,j(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 ${K} (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 r=pe(t.content??await n.readFile(e.absPath,`utf-8`),{tokens:this.config.chunkTokens,overlap:this.config.chunkOverlap}).filter(e=>e.text.trim().length>0);t.source===`sessions`&&me(r,t.lineMap);let i=await this.embedChunks(r),a=i.find(e=>e.length>0),o=a?await this.ensureVectorReady(a.length):!1,s=Date.now();if(o)try{this.db.prepare(`DELETE FROM ${W} 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 ${G} 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 n=0;n<r.length;n+=1){let a=r[n],c=i[n]??[],l=A(`${t.source}:${e.path}:${a.startLine}:${a.endLine}:${a.hash}:${this.provider.model}`);if(this.db.prepare(`INSERT INTO chunks (id, path, source, start_line, end_line, hash, model, text, embedding, updated_at)
|
|
57
57
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
58
58
|
ON CONFLICT(id) DO UPDATE SET
|
|
59
59
|
hash=excluded.hash,
|
|
@@ -65,5 +65,5 @@ import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{createRequire as t}fro
|
|
|
65
65
|
source=excluded.source,
|
|
66
66
|
hash=excluded.hash,
|
|
67
67
|
mtime=excluded.mtime,
|
|
68
|
-
size=excluded.size`).run(e.path,t.source,e.hash,e.mtimeMs,e.size)}buildSourceFilter(){let e=this.config.sources;return e.length?{sql:` AND source IN (${e.map(()=>`?`).join(`, `)})`,params:e}:{sql:``,params:[]}}async searchVector(e,t){return await
|
|
69
|
-
`):[]},listFiles:async()=>
|
|
68
|
+
size=excluded.size`).run(e.path,t.source,e.hash,e.mtimeMs,e.size)}buildSourceFilter(){let e=this.config.sources;return e.length?{sql:` AND source IN (${e.map(()=>`?`).join(`, `)})`,params:e}:{sql:``,params:[]}}async searchVector(e,t){return await Re({db:this.db,vectorTable:W,providerModel:this.provider.model,queryVec:e,limit:t,snippetMaxChars:700,ensureVectorReady:async e=>await this.ensureVectorReady(e),sourceFilterVec:this.buildSourceFilter(),sourceFilterChunks:this.buildSourceFilter()})}async searchKeyword(e,t){return this.ftsAvailable?await Be({db:this.db,ftsTable:G,providerModel:this.provider.model,query:e,limit:t,snippetMaxChars:700,sourceFilter:this.buildSourceFilter(),buildFtsQuery:e=>Ne(e),bm25RankToScore:Pe}):[]}resetIndex(){if(this.db.exec(`DELETE FROM files`),this.db.exec(`DELETE FROM chunks`),this.ftsAvailable)try{this.db.exec(`DELETE FROM ${G}`)}catch{}this.dropVectorTable(),this.vector.dims=void 0,this.sessionsDirtyFiles.clear()}async sync(e){let t=this.readMeta(),n=!t||t.model!==this.provider.model||t.provider!==this.provider.id||t.providerKey!==this.providerKey||t.chunkTokens!==this.config.chunkTokens||t.chunkOverlap!==this.config.chunkOverlap||this.vector.available&&!t?.vectorDims;n&&this.resetIndex();let r=await k(this.memoryRoot),i=(await Promise.all(r.map(async e=>fe(e,this.memoryRoot)))).filter(e=>e!==null),a=new Set(i.map(e=>e.path)),o=i.map(e=>async()=>{let t=this.db.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`).get(e.path,`memory`);!n&&t?.hash===e.hash||await this.indexFile(e,{source:`memory`})});for(let e of o)await e();let s=this.db.prepare(`SELECT path FROM files WHERE source = ?`).all(`memory`);for(let e of s)if(!a.has(e.path)){this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(e.path,`memory`);try{this.db.prepare(`DELETE FROM ${W} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(e.path,`memory`)}catch{}if(this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(e.path,`memory`),this.ftsAvailable)try{this.db.prepare(`DELETE FROM ${G} WHERE path = ? AND source = ? AND model = ?`).run(e.path,`memory`,this.provider.model)}catch{}}this.config.experimental.sessionMemory&&(n||this.sessionsDirty)&&await this.syncSessionFiles(n),this.writeMeta({model:this.provider.model,provider:this.provider.id,providerKey:this.providerKey,chunkTokens:this.config.chunkTokens,chunkOverlap:this.config.chunkOverlap,...this.vector.available&&this.vector.dims?{vectorDims:this.vector.dims}:{}}),this.dirty=!1}async syncSessionFiles(e){let t=await U(this.dataDir,this.sessionStoreName),n=(await Promise.all(t.map(async e=>Ke(this.dataDir,e,this.sessionStoreName)))).filter(e=>e!==null),r=new Set(n.map(e=>e.path)),i=e||this.sessionsDirtyFiles.size===0;for(let t of n){if(!i&&!this.sessionsDirtyFiles.has(t.absPath))continue;let n=this.db.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`).get(t.path,`sessions`);if(!e&&n?.hash===t.hash){this.resetSessionDelta(t.absPath,t.size);continue}await this.indexFile(t,{source:`sessions`,content:t.content,lineMap:t.lineMap}),this.resetSessionDelta(t.absPath,t.size)}let a=this.db.prepare(`SELECT path FROM files WHERE source = ?`).all(`sessions`);for(let e of a)if(!r.has(e.path)){this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(e.path,`sessions`);try{this.db.prepare(`DELETE FROM ${W} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`).run(e.path,`sessions`)}catch{}if(this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(e.path,`sessions`),this.ftsAvailable)try{this.db.prepare(`DELETE FROM ${G} WHERE path = ? AND source = ? AND model = ?`).run(e.path,`sessions`,this.provider.model)}catch{}}this.sessionsDirty=!1,this.sessionsDirtyFiles.clear()}resetSessionDelta(e,t){let n=this.sessionDeltas.get(e);n&&(n.lastSize=t,n.pendingBytes=0,n.pendingMessages=0)}decorateCitations(e){return this.config.citations===`off`?e:e.map(e=>{let t=`Source: ${e.path}#L${e.startLine}-L${e.endLine}`;return this.config.citations===`on`?{...e,citation:t,snippet:`${e.snippet}\n\n${t}`}:{...e,citation:t}})}},Q=e({createBuiltinMemoryProvider:()=>$});function $(e,t){let n=Z.get(e.dataDir,t?.includeSessions?{experimental:{sessionMemory:!0},sources:[`memory`,`sessions`],store:{sessionStoreName:e.sessionStoreName,vector:{enabled:!0}}}:e.sessionStoreName?{store:{sessionStoreName:e.sessionStoreName,vector:{enabled:!0}}}:void 0),i=e.memoryDir;return{id:`builtin-memory`,name:`Builtin Memory Provider`,status:()=>n.status(),search:async(e,t)=>n.search(e),getLines:async(e,t,r)=>{let i=Math.max(1,r-t+1),a=await n.readFile({relPath:e,from:t,lines:i});return a.text?a.text.split(`
|
|
69
|
+
`):[]},listFiles:async()=>k(i),append:async e=>n.appendToMemory(e),updateFile:async(e,t)=>{await n.replaceFile({relPath:e,content:t})},deleteFile:async e=>{await n.deleteFile(e)},sync:async e=>{await n.sync({reason:e??`provider-sync`})},noteSessionUpdate:e=>{let t=r.isAbsolute(e)?e:r.resolve(e);n.noteSessionUpdate(t)}}}export{m as A,b as C,S as D,ne as E,g as M,d as N,u as O,ae as P,C as S,c as T,T as _,ye as a,ie as b,s as c,h as d,p as f,E as g,y as h,ve as i,l as j,se as k,re as l,_ as m,$ as n,F as o,ee as p,Z as r,k as s,Q as t,te as u,oe as v,f as w,w as x,x as y};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { S as AgentsConfig, _ as saveAgentsConfig, a as listAgents, b as AgentConfig, c as normalizeAgentId, d as resolveAgentDir, f as resolveAgentIdByBinding, g as resolveModelString, h as resolveModelFallbacks, i as getAgentConfig, l as removeAgent, m as resolveDefaultAgentId, n as addBinding, o as listBindings, p as resolveAgentsConfigPath, s as loadAgentsConfig, t as addAgent, u as removeBindings, v as updateAgentIdentity, x as AgentModelConfig, y as AgentBinding } from "./index-pXTy2jgd.js";
|
|
2
2
|
import * as _gencode_shared0 from "@gencode/shared";
|
|
3
|
-
import { AgentCustomProgressEvent, AgentProgressEvent, AgentProgressEvent as AgentProgressEvent$1, AgentProgressEvent as AgentProgressEvent$2, CallbackEventPayload, CallbackEventPayload as CallbackEventPayload$1, Channel, Channel as Channel$1, CollapseSpan, HitlCheckpoint, HitlCheckpoint as HitlCheckpoint$1, HitlHistoryEntry, HitlRequest, HitlRequest as HitlRequest$1, HitlResolution, HitlResolution as HitlResolution$1, HitlStatus, HitlToolContext, HitlToolContext as HitlToolContext$1, ModelUsageCheckpoint, PausedRunState, PausedRunState as PausedRunState$1, ReadStateRecord, RunResultPayload, RunResultPayload as RunResultPayload$1, SessionContextSnapshot, SessionMemorySnapshot, SnipRecord, ToolResultReference, UiToolExtra, UiToolOutputSchema, UiToolPausedState, UiToolRequest, UiToolResult, UiToolValidationResult } from "@gencode/shared";
|
|
3
|
+
import { AgentCustomProgressEvent, AgentProgressEvent, AgentProgressEvent as AgentProgressEvent$1, AgentProgressEvent as AgentProgressEvent$2, CallbackEventPayload, CallbackEventPayload as CallbackEventPayload$1, Channel, Channel as Channel$1, CollapseSpan, HitlCheckpoint, HitlCheckpoint as HitlCheckpoint$1, HitlHistoryEntry, HitlRequest, HitlRequest as HitlRequest$1, HitlResolution, HitlResolution as HitlResolution$1, HitlStatus, HitlToolContext, HitlToolContext as HitlToolContext$1, ModelUsageCheckpoint, PausedRunState, PausedRunState as PausedRunState$1, ReadStateRecord, RunResultPayload, RunResultPayload as RunResultPayload$1, SessionContextSnapshot, SessionMemorySnapshot, SessionMetadata, SessionMetadata as SessionMetadata$1, SessionSummary, SessionSummary as SessionSummary$1, SnipRecord, ToolResultReference, UiToolExtra, UiToolOutputSchema, UiToolPausedState, UiToolRequest, UiToolResult, UiToolValidationResult } from "@gencode/shared";
|
|
4
4
|
import { AssistantMessage, Message } from "@mariozechner/pi-ai";
|
|
5
5
|
import { AgentMessage, AgentTool } from "@mariozechner/pi-agent-core";
|
|
6
6
|
|
|
@@ -171,11 +171,6 @@ type AgentRunParamsBase = {
|
|
|
171
171
|
messaging?: {
|
|
172
172
|
enabled?: boolean; /** Human-readable configured channel list */
|
|
173
173
|
channels?: string[];
|
|
174
|
-
}; /** Documentation context for prompt guidance */
|
|
175
|
-
docs?: {
|
|
176
|
-
localPath?: string;
|
|
177
|
-
webUrl?: string;
|
|
178
|
-
sourceUrl?: string;
|
|
179
174
|
};
|
|
180
175
|
/**
|
|
181
176
|
* Maximum number of recent user turns to include in context.
|
|
@@ -308,6 +303,8 @@ declare class SubagentRegistry {
|
|
|
308
303
|
* and marks them as announced so they are not returned again.
|
|
309
304
|
*/
|
|
310
305
|
consumeCompleted(parentSessionId: string): SubagentRunRecord[];
|
|
306
|
+
/** Marks a finished run as already delivered to its parent. */
|
|
307
|
+
markAnnounced(runId: string): void;
|
|
311
308
|
/** Returns true if there are completed runs not yet returned by consumeCompleted. */
|
|
312
309
|
hasUnannounced(parentSessionId: string): boolean;
|
|
313
310
|
/**
|
|
@@ -701,8 +698,8 @@ declare function generateSessionTitle(params: GenerateTitleParams): Promise<stri
|
|
|
701
698
|
//#region src/runner/runner.d.ts
|
|
702
699
|
/**
|
|
703
700
|
* Runs an agent session end-to-end.
|
|
704
|
-
* Supports multi-agent: subagents
|
|
705
|
-
*
|
|
701
|
+
* Supports multi-agent: subagent_spawn runs subagents as blocking tool calls.
|
|
702
|
+
* The announce loop remains for records injected by non-tool entry points.
|
|
706
703
|
*
|
|
707
704
|
* @param params - Run parameters.
|
|
708
705
|
* @param _registryForTesting - Internal: inject a pre-populated registry for unit tests.
|
|
@@ -714,23 +711,9 @@ declare const DEFAULT_SESSION_STORE_NAME = "sessions";
|
|
|
714
711
|
type SessionPathOptions = {
|
|
715
712
|
storeName?: string;
|
|
716
713
|
};
|
|
717
|
-
type SessionMetadata = {
|
|
718
|
-
id: string;
|
|
719
|
-
title: string;
|
|
720
|
-
channel: Channel;
|
|
721
|
-
createdAt: string;
|
|
722
|
-
updatedAt: string;
|
|
723
|
-
};
|
|
724
|
-
type SessionSummary = {
|
|
725
|
-
id: string;
|
|
726
|
-
title: string;
|
|
727
|
-
channel: Channel;
|
|
728
|
-
createdAt: string;
|
|
729
|
-
updatedAt: string;
|
|
730
|
-
};
|
|
731
714
|
type SessionInspection = {
|
|
732
715
|
id: string;
|
|
733
|
-
metadata: SessionMetadata | null;
|
|
716
|
+
metadata: SessionMetadata$1 | null;
|
|
734
717
|
transcriptPath: string;
|
|
735
718
|
contextSnapshotPath: string;
|
|
736
719
|
sessionMemoryPath: string;
|
|
@@ -744,7 +727,7 @@ type SessionInspection = {
|
|
|
744
727
|
};
|
|
745
728
|
type SessionExport = {
|
|
746
729
|
id: string;
|
|
747
|
-
metadata: SessionMetadata | null;
|
|
730
|
+
metadata: SessionMetadata$1 | null;
|
|
748
731
|
transcript: TranscriptEntry[];
|
|
749
732
|
context: SessionContextSnapshot;
|
|
750
733
|
paths: {
|
|
@@ -802,13 +785,13 @@ declare function loadCronExecutionRecords(dataDir: string, sessionId: string, op
|
|
|
802
785
|
/** Lists all session IDs within a data directory */
|
|
803
786
|
declare function listSessions(dataDir: string, options?: SessionPathOptions): Promise<string[]>;
|
|
804
787
|
/** Saves session metadata to disk */
|
|
805
|
-
declare function saveSessionMetadata(dataDir: string, metadata: SessionMetadata, options?: SessionPathOptions): Promise<void>;
|
|
806
|
-
type SessionMetadataUpdate = Partial<Omit<SessionMetadata, "id" | "createdAt">>;
|
|
807
|
-
declare function updateSessionMetadata(dataDir: string, sessionId: string, updates: SessionMetadataUpdate, options?: SessionPathOptions): Promise<SessionMetadata | null>;
|
|
788
|
+
declare function saveSessionMetadata(dataDir: string, metadata: SessionMetadata$1, options?: SessionPathOptions): Promise<void>;
|
|
789
|
+
type SessionMetadataUpdate = Partial<Omit<SessionMetadata$1, "id" | "createdAt">>;
|
|
790
|
+
declare function updateSessionMetadata(dataDir: string, sessionId: string, updates: SessionMetadataUpdate, options?: SessionPathOptions): Promise<SessionMetadata$1 | null>;
|
|
808
791
|
/** Loads session metadata from disk; returns null if not found */
|
|
809
|
-
declare function loadSessionMetadata(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise<SessionMetadata | null>;
|
|
792
|
+
declare function loadSessionMetadata(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise<SessionMetadata$1 | null>;
|
|
810
793
|
/** Lists all sessions with their metadata summaries, optionally filtered by channel */
|
|
811
|
-
declare function listSessionSummaries(dataDir: string, channel?: Channel, options?: SessionPathOptions): Promise<SessionSummary[]>;
|
|
794
|
+
declare function listSessionSummaries(dataDir: string, channel?: Channel, options?: SessionPathOptions): Promise<SessionSummary$1[]>;
|
|
812
795
|
declare function loadSessionContextSnapshot(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise<SessionContextSnapshot>;
|
|
813
796
|
declare function inspectSession(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise<SessionInspection>;
|
|
814
797
|
declare function exportSession(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise<SessionExport>;
|
|
@@ -930,7 +913,7 @@ declare const BOOTSTRAP_MAX_CHARS = 20000;
|
|
|
930
913
|
/** Maximum total characters across all bootstrap files */
|
|
931
914
|
declare const BOOTSTRAP_TOTAL_MAX_CHARS = 150000;
|
|
932
915
|
/** Names of bootstrap identity files, in injection order */
|
|
933
|
-
declare const BOOTSTRAP_FILE_NAMES: readonly ["AGENTS.md", "SOUL.md", "TOOLS.md", "IDENTITY.md", "USER.md", "
|
|
916
|
+
declare const BOOTSTRAP_FILE_NAMES: readonly ["AGENTS.md", "SOUL.md", "TOOLS.md", "IDENTITY.md", "USER.md", "MEMORY.md", "BOOTSTRAP.md"];
|
|
934
917
|
/** A loaded (or missing) bootstrap file */
|
|
935
918
|
type BootstrapFile = {
|
|
936
919
|
name: string;
|
|
@@ -1162,7 +1145,6 @@ declare function listAvailableSlashCommands(skills: Skill[]): SlashCommandList;
|
|
|
1162
1145
|
//#region src/system-prompt/builder.d.ts
|
|
1163
1146
|
type PromptMode = "full" | "minimal" | "none";
|
|
1164
1147
|
type MemoryCitationsMode = "off" | "on";
|
|
1165
|
-
/** Parameters for building the agent system prompt */
|
|
1166
1148
|
type SystemPromptParams = {
|
|
1167
1149
|
dataDir: string;
|
|
1168
1150
|
skills?: Skill[];
|
|
@@ -1176,7 +1158,6 @@ type SystemPromptParams = {
|
|
|
1176
1158
|
toolNames?: string[];
|
|
1177
1159
|
toolSummaries?: Record<string, string>;
|
|
1178
1160
|
promptMode?: PromptMode;
|
|
1179
|
-
heartbeatPrompt?: string;
|
|
1180
1161
|
bootstrapWarnings?: string[];
|
|
1181
1162
|
memoryCitationsMode?: MemoryCitationsMode;
|
|
1182
1163
|
sandboxInfo?: {
|
|
@@ -1188,13 +1169,9 @@ type SystemPromptParams = {
|
|
|
1188
1169
|
enabled?: boolean;
|
|
1189
1170
|
channels?: string[];
|
|
1190
1171
|
};
|
|
1191
|
-
docs?: {
|
|
1192
|
-
localPath?: string;
|
|
1193
|
-
webUrl?: string;
|
|
1194
|
-
sourceUrl?: string;
|
|
1195
|
-
};
|
|
1196
1172
|
currentDate?: string;
|
|
1197
|
-
timezone?: string;
|
|
1173
|
+
timezone?: string; /** Override for the preset system prompt (opening paragraph). */
|
|
1174
|
+
presetSystemPrompt?: string;
|
|
1198
1175
|
/**
|
|
1199
1176
|
* Summary of prior conversation history produced by compaction.
|
|
1200
1177
|
* When provided, it is appended to the system prompt so the agent
|
|
@@ -1410,6 +1387,52 @@ declare const memoryAppendSchema: TObject<{
|
|
|
1410
1387
|
declare function createMemoryAppendTool(dataDir: string, options?: MemoryToolOptions): AgentTool<typeof memoryAppendSchema, {
|
|
1411
1388
|
appended: boolean;
|
|
1412
1389
|
}>;
|
|
1390
|
+
declare const memoryWriteSchema: TObject<{
|
|
1391
|
+
section: TString;
|
|
1392
|
+
content: TString;
|
|
1393
|
+
mode: TUnion<[TLiteral<"append">, TLiteral<"replace">]>;
|
|
1394
|
+
}>;
|
|
1395
|
+
declare function createMemoryWriteTool(dataDir: string, options?: MemoryToolOptions): AgentTool<typeof memoryWriteSchema, {
|
|
1396
|
+
section: string;
|
|
1397
|
+
mode: string;
|
|
1398
|
+
}>;
|
|
1399
|
+
declare const memoryLogSchema: TObject<{
|
|
1400
|
+
content: TString;
|
|
1401
|
+
scope: TOptional<TUnion<[TLiteral<"daily">, TLiteral<"session">]>>;
|
|
1402
|
+
}>;
|
|
1403
|
+
declare function createMemoryLogTool(dataDir: string, options?: MemoryToolOptions): AgentTool<typeof memoryLogSchema, {
|
|
1404
|
+
date: string;
|
|
1405
|
+
scope: string;
|
|
1406
|
+
}>;
|
|
1407
|
+
declare const memoryListSchema: TObject<{
|
|
1408
|
+
scope: TOptional<TUnion<[TLiteral<"long-term">, TLiteral<"recent">, TLiteral<"all">]>>;
|
|
1409
|
+
}>;
|
|
1410
|
+
declare function createMemoryListTool(dataDir: string, options?: MemoryToolOptions): AgentTool<typeof memoryListSchema, {
|
|
1411
|
+
count: number;
|
|
1412
|
+
scope: string;
|
|
1413
|
+
files: Array<{
|
|
1414
|
+
file: string;
|
|
1415
|
+
content: string;
|
|
1416
|
+
}>;
|
|
1417
|
+
}>;
|
|
1418
|
+
declare const memoryForgetSchema: TObject<{
|
|
1419
|
+
id: TOptional<TString>;
|
|
1420
|
+
query: TOptional<TString>;
|
|
1421
|
+
limit: TOptional<TNumber>;
|
|
1422
|
+
scope: TOptional<TUnion<[TLiteral<"long-term">, TLiteral<"recent">, TLiteral<"all">]>>;
|
|
1423
|
+
}>;
|
|
1424
|
+
declare function createMemoryForgetTool(dataDir: string, options?: MemoryToolOptions): AgentTool<typeof memoryForgetSchema, {
|
|
1425
|
+
removed: number;
|
|
1426
|
+
id?: string;
|
|
1427
|
+
query?: string;
|
|
1428
|
+
}>;
|
|
1429
|
+
declare const memoryUpdateSchema: TObject<{
|
|
1430
|
+
id: TString;
|
|
1431
|
+
content: TString;
|
|
1432
|
+
}>;
|
|
1433
|
+
declare function createMemoryUpdateTool(dataDir: string, options?: MemoryToolOptions): AgentTool<typeof memoryUpdateSchema, {
|
|
1434
|
+
id: string;
|
|
1435
|
+
}>;
|
|
1413
1436
|
//#endregion
|
|
1414
1437
|
//#region src/tools/process-registry.d.ts
|
|
1415
1438
|
type ProcessStatus = "running" | "completed" | "failed" | "killed" | "timeout";
|
|
@@ -1612,15 +1635,22 @@ declare const spawnSchema: TObject<{
|
|
|
1612
1635
|
label: TOptional<TString>;
|
|
1613
1636
|
}>;
|
|
1614
1637
|
type SpawnResult = {
|
|
1615
|
-
status: "
|
|
1638
|
+
status: "done";
|
|
1616
1639
|
childSessionId: string;
|
|
1617
1640
|
runId: string;
|
|
1618
|
-
|
|
1641
|
+
result: string;
|
|
1619
1642
|
} | {
|
|
1620
1643
|
status: "forbidden";
|
|
1621
1644
|
error: string;
|
|
1622
1645
|
} | {
|
|
1623
1646
|
status: "error";
|
|
1647
|
+
childSessionId?: string;
|
|
1648
|
+
runId?: string;
|
|
1649
|
+
error: string;
|
|
1650
|
+
} | {
|
|
1651
|
+
status: "killed";
|
|
1652
|
+
childSessionId: string;
|
|
1653
|
+
runId: string;
|
|
1624
1654
|
error: string;
|
|
1625
1655
|
};
|
|
1626
1656
|
/** Formats the announce message injected into the parent session when a subagent completes. */
|
|
@@ -1632,7 +1662,7 @@ declare function buildSubagentAnnounceMessage(params: {
|
|
|
1632
1662
|
error?: string;
|
|
1633
1663
|
}): string;
|
|
1634
1664
|
/**
|
|
1635
|
-
* Creates the
|
|
1665
|
+
* Creates the subagent_spawn tool that allows an agent to delegate tasks to subagents.
|
|
1636
1666
|
*
|
|
1637
1667
|
* @param registry The parent session's subagent registry.
|
|
1638
1668
|
* @param parentSessionId Session ID of the agent doing the spawning.
|
|
@@ -1643,7 +1673,7 @@ declare function buildSubagentAnnounceMessage(params: {
|
|
|
1643
1673
|
* @param loopDetection Tool-loop detection config inherited from the parent.
|
|
1644
1674
|
* @param spawnFn Function that actually runs a child agent (injected to avoid circular imports).
|
|
1645
1675
|
*/
|
|
1646
|
-
declare function
|
|
1676
|
+
declare function createSubagentSpawnTool(registry: SubagentRegistry, parentSessionId: string, depth: number, dataDir: string, channel: AgentRunParams["channel"], llm: AgentRunParams["llm"], loopDetection: ToolLoopDetectionConfig | undefined, inheritedRunParams: Pick<AgentRunParams, "plugins" | "memory" | "messaging" | "historyLimit" | "onProgress" | "messageId" | "sessionStoreName">, spawnFn: (params: AgentRunParams) => Promise<AgentRunResult>): AgentTool<typeof spawnSchema, SpawnResult>;
|
|
1647
1677
|
//#endregion
|
|
1648
1678
|
//#region src/tools/subagents.d.ts
|
|
1649
1679
|
declare const ACTIONS: readonly ["list", "kill"];
|
|
@@ -1751,7 +1781,7 @@ type SubagentToolsContext = {
|
|
|
1751
1781
|
depth: number;
|
|
1752
1782
|
channel: AgentRunParams["channel"];
|
|
1753
1783
|
llm: AgentRunParams["llm"];
|
|
1754
|
-
inheritedRunParams?: Pick<AgentRunParams, "plugins" | "memory" | "messaging" | "
|
|
1784
|
+
inheritedRunParams?: Pick<AgentRunParams, "plugins" | "memory" | "messaging" | "historyLimit" | "onProgress" | "messageId" | "sessionStoreName">;
|
|
1755
1785
|
loopDetection?: ToolLoopDetectionConfig;
|
|
1756
1786
|
memoryOptions?: MemoryToolOptions;
|
|
1757
1787
|
pluginSkillDirs?: string[];
|
|
@@ -1767,7 +1797,7 @@ type SubagentToolsContext = {
|
|
|
1767
1797
|
* File and exec/process tools are scoped to the workspace directory.
|
|
1768
1798
|
* Memory tools are scoped to the data directory's .aimax root
|
|
1769
1799
|
* (MEMORY.md + memory/*.md).
|
|
1770
|
-
* Subagent tools (
|
|
1800
|
+
* Subagent tools (subagent_spawn, subagents) are included when ctx is provided.
|
|
1771
1801
|
*/
|
|
1772
1802
|
declare function createAgentTools(dataDir: string, ctx?: SubagentToolsContext): AgentTool[];
|
|
1773
1803
|
//#endregion
|
|
@@ -2220,4 +2250,4 @@ declare function formatClarifyResolution(resolution: HitlResolution): string;
|
|
|
2220
2250
|
declare function formatReviewResolution(resolution: HitlResolution): string;
|
|
2221
2251
|
declare function buildResumeNarration(resolution: HitlResolution, kind: string): string;
|
|
2222
2252
|
//#endregion
|
|
2223
|
-
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, type CronExecutionRecord, 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 SkillDirectory, type SkillViewResult, type SlashCommandList, type SubagentContext, SubagentRegistry, type SubagentRunRecord, type SubagentStatus, type SubagentToolsContext, type SystemPromptParams, type ToolLoopDetectionConfig, type TranscriptEntry, type UiToolInputSchema, type UiToolOptions, UiToolPauseSignal, addAgent, addBinding, aimaxDir, appendCronExecutionRecord, 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,
|
|
2253
|
+
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, type CronExecutionRecord, 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 SkillDirectory, type SkillViewResult, type SlashCommandList, type SubagentContext, SubagentRegistry, type SubagentRunRecord, type SubagentStatus, type SubagentToolsContext, type SystemPromptParams, type ToolLoopDetectionConfig, type TranscriptEntry, type UiToolInputSchema, type UiToolOptions, UiToolPauseSignal, addAgent, addBinding, aimaxDir, appendCronExecutionRecord, appendToMemory, appendTranscriptEntry, approvalSummaryFromResolution, bootstrapMountLayout, buildBootstrapContextFiles, buildResumeNarration, buildSkillsPrompt, buildSubagentAnnounceMessage, buildSystemPrompt, cleanupOldSubagentRecords, clearPendingHitl, clearPendingUiTool, collapseLogPath, contextSnapshotPath, createAgentTools, createApplyPatchTool, createBashTool, createBuiltinMemoryProvider, createContextManager, createEditFileTool, createExecTool, createImageTool, createListDirTool, createMemoryAppendTool, createMemoryForgetTool, createMemoryGetTool, createMemoryListTool, createMemoryLogTool, createMemorySearchTool, createMemoryUpdateTool, createMemoryWriteTool, createPendingHitl, createPendingUiTool, createPluginProgressEmitter, createPluginRuntime, createProcessTool, createReadFileTool, createSession, createSessionContextStore, createSkillListTool, createSkillLoadTool, createSubagentSpawnTool, createSubagentsTool, createUiTool, createWriteFileTool, cronExecutionsPath, defaultUiToolInputSchema, deleteMemoryFile, discoverAIMaxPlugins, ensureBootstrapMountLayout, ensureSession, exportSession, findSkillByName, formatApprovalResolution, formatClarifyResolution, formatReviewResolution, generateSessionTitle, getAgentConfig, getMemoryLines, hasBootstrapSentinel, hitlHistoryPath, initializePluginSystem, inspectBootstrapMountLayout, inspectSession, isBootstrapMountLayoutReady, isHitlPauseSignal, isUiToolPauseSignal, listAgents, listAvailableSlashCommands, listBindings, listMemoryFiles, listSessionSummaries, listSessions, listSubagentRunsFromDisk, loadAgentsConfig, loadBootstrapFiles, loadCronExecutionRecords, readPendingHitl as loadPendingHitl, readPendingHitl, readPendingUiTool as loadPendingUiTool, readPendingUiTool, loadPluginManifest, loadPluginManifestRegistry, loadPlugins, loadSessionContextSnapshot, loadSessionMetadata, loadSkillView, loadSkills, loadSkillsFromDirs, loadSkillsWithPluginDirs, loadSubagentRegistryFromDisk, loadTranscript, memoryDir, metadataPath, normalizeAgentId, normalizePluginsConfig, normalizeSessionStoreName, 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 };
|