@gencode/agents 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,9 @@
4
4
 
5
5
  ### Patch Changes
6
6
 
7
+ - 5661a10: Temporarily omit effective custom agents from agent prompts and the subagent spawn tool contract.
8
+ - Persist assistant transcript entries as soon as a blocking `subagent_spawn` assistant message is complete, while still appending the corresponding `tool_result` entries after the subagents settle.
9
+ - b4687b0: Report subagent runs that return runner errors as failed instead of completed.
7
10
  - 4325f90: Store spawned subagent sessions under their parent session using the spawn tool call id as the child session id.
8
11
 
9
12
  ## 0.3.0
package/dist/index.d.ts CHANGED
@@ -1809,7 +1809,6 @@ declare function createImageTool(): AgentTool<typeof imageSchema, ImageResult>;
1809
1809
  declare const spawnSchema: TObject<{
1810
1810
  task: TString;
1811
1811
  label: TOptional<TString>;
1812
- agent: TOptional<TString>;
1813
1812
  }>;
1814
1813
  type SpawnResult = {
1815
1814
  status: "done";
package/dist/index.js CHANGED
@@ -3,9 +3,7 @@ import{A as e,C as t,D as n,E as r,M as i,N as a,O as o,P as s,S as c,T as l,_ a
3
3
  `),truncated:!0,originalLength:r.length}}function Qe(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function $e(e,t){let n=t?.maxChars??Ke,r=Math.max(1,t?.totalMaxChars??Math.max(n,qe)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=Qe(`[MISSING] Expected at: ${a.path}`,r);if(!e)break;r=Math.max(0,r-e.length),i.push({path:a.path,content:e});continue}if(r<64){t?.warn?.(`remaining bootstrap budget is ${r} chars (<64); skipping additional files`);break}let e=Math.max(1,Math.min(n,r)),{result:o,truncated:s,originalLength:c}=Ze(a.content??``,a.name,e),l=Qe(o,r);l&&((s||l.length<o.length)&&t?.warn?.(`bootstrap file ${a.name} is ${c} chars (limit ${e}); truncating`),r=Math.max(0,r-l.length),i.push({path:a.path,content:l}))}return i}const et=`You are a personal assistant running inside AiMax.`;async function tt(e){try{return{presetSystemPrompt:be(await z.readFile(e,`utf-8`)).content.trim()||et}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:et};throw e}}async function nt(){return tt(`/aimax/system_prompt.md`)}function rt(e){return B.join(e,`.aimax`,`skills`)}function it(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function at(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${it(n)}\n`)}function ot(e){let t=be(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
4
4
  `);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}async function st(e){return lt([rt(e)])}async function ct(e,t,n=[]){return lt([...n,...t,rt(e)])}async function lt(e){let t=new Map;for(let n of e){let e;try{e=await z.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let r=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of r.sort()){let r=B.join(n,e,`SKILL.md`),i;try{i=await z.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a;try{a=ot(i)}catch(t){at(e,r,t);continue}t.set(e,{name:e,description:a,location:r})}}return Array.from(t.values()).slice(0,50)}async function ut(e,t){let n=t.trim();if(!n)return;let r=(await lt(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:B.dirname(r.location)}}async function dt(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=B.resolve(r),a=B.basename(i)===`SKILL.md`?i:B.join(i,`SKILL.md`);if(B.basename(a)!==`SKILL.md`)return;let o;try{o=await z.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s;try{s=ot(o)}catch(e){at(n,a,e);return}return{skill:{name:n,description:s,location:a},rootDir:B.dirname(a)}}async function ft(e,t,n){let r=n?.trim()?await dt(t,n):await ut(e,t);if(!r)return;let i=await z.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function pt(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
5
5
  `)).join(`
6
- `)}\n</available_skills>`}const mt=`/aimax/agents`,ht=/^[a-z]+(?:-[a-z]+)*$/;function gt(e){let t=[{dir:e.systemAgentsDir??mt,source:`system`},{dir:B.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:B.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function _t(e){let t=new Map;for(let n of gt(e)){let e=await vt(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}async function vt(e,t){let n;try{n=await z.readdir(e,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}let r=[];for(let i of n){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let n=B.join(e,i.name),a=yt(await z.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function yt(e,t){let n=be(e),r=Tt(n.data.name)?.trim(),i=Tt(n.data.description)?.trim();if(!r||!ht.test(r)||!i)return;let a=Tt(n.data.model)?.trim(),o=Tt(n.data.initPrompt)?.trim()??Tt(n.data.initialPrompt)?.trim(),s=Et(n.data.maxTurns),c=Dt(n.data.tools),l=Dt(n.data.disallowedTools),u=Dt(n.data.skills);return{name:r,description:i,...c?{tools:c}:{},...l?{disallowedTools:l}:{},...a&&a!==`inherit`?{model:a}:{},...s?{maxTurns:s}:{},...o?{initPrompt:o}:{},...u?{skills:u}:{},systemPrompt:n.content.trim(),sourcePath:t.sourcePath,source:t.source}}function bt(e,t){let n=t?.trim();if(n)return e.find(e=>e.name===n)}function xt(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function St(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Ot)):void 0,r=new Set((t.disallowedTools??[]).map(Ot));return e.filter(e=>{let t=typeof e.name==`string`?Ot(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Ct(e){return e.length===0?``:[`## Custom Agents`,"The following custom agents are currently effective. Use `subagent_spawn` with the agent name when one clearly matches the delegated task.",e.map(e=>`- ${e.name}: ${e.description}`).join(`
7
- `),``].join(`
8
- `)}function wt(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Tt(e){return typeof e==`string`?e:void 0}function Et(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Dt(e){let t;if(typeof e==`string`)t=e.split(`,`);else if(Array.isArray(e))t=e.filter(e=>typeof e==`string`);else return;let n=t.map(e=>e.trim()).filter(Boolean);return n.length>0?n:void 0}function Ot(e){let t=e.trim();return{bash:`exec`,read:`read_file`,write:`write_file`,edit:`edit_file`,multiedit:`edit_file`,glob:`list_dir`,grep:`exec`}[t.toLowerCase()]??t}function kt(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function At(e=new Date){let t=kt(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let jt=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),Mt=null;function Nt(){return At()}function Pt(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function Ft(e){return B.join(e,`.aimax`)}function It(e){return{appLogPath:B.join(e,`app.log`),errorLogPath:B.join(e,`errors.log`)}}function Lt(e){let{appLogPath:t,errorLogPath:n}=It(e);xe.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function Rt(e,t,n){return`[${Nt()}] [${e}] ${t}${Pt(n)}`}function zt(e,t,n){process.stderr.write(`${Rt(e,t,n)}\n`)}function Bt(e,t,n){if(!Mt){zt(e,t,n);return}let r=Rt(e,t,n),i=xe.getLogger();if(e===jt.ERROR){i.error(r);return}if(e===jt.WARN){i.warn(r);return}i.info(r)}function Vt(e){let t=Ft(e);Mt?.dataDir!==e&&(V.mkdirSync(t,{recursive:!0}),Lt(t),Mt={dataDir:e,logDir:t})}const U={info:(e,t)=>Bt(jt.INFO,e,t),warn:(e,t)=>Bt(jt.WARN,e,t),error:(e,t)=>Bt(jt.ERROR,e,t)};function Ht(e,t=240){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}const Ut=3,Wt=5;var Gt=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),U.info(`subagent status changed`,{runId:e.runId,status:`running`,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,taskLength:e.task.length,taskPreview:Ht(e.task),startedAt:e.startedAt})}complete(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`done`,n.record.result=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}fail(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`error`,n.record.error=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}kill(e){let t=this.entries.get(e);return!t||t.record.status!==`running`?!1:(t.record.abortController.abort(),t.record.status=`killed`,t.record.endedAt=Date.now(),this.logTerminalStatus(t.record),!0)}killAll(e){let t=0;for(let{record:n}of this.entries.values())n.parentSessionId===e&&n.status===`running`&&(n.abortController.abort(),n.status=`killed`,n.endedAt=Date.now(),this.logTerminalStatus(n),t++);return t}list(e){return Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e).map(e=>e.record)}hasPending(e){return this.list(e).some(e=>e.status===`running`)}countActive(e){return this.list(e).filter(e=>e.status===`running`).length}async waitForAll(e){let t=Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e&&t.record.status===`running`).map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}peekCompleted(e){return this.list(e).filter(e=>e.status!==`running`&&!this.announced.has(e.runId))}consumeCompleted(e){let t=this.peekCompleted(e);return this.markAnnounced(t.map(e=>e.runId)),t}markAnnounced(e){let t=Array.isArray(e)?e:[e];for(let e of t){this.announced.add(e);let t=this.entries.get(e)?.record;t&&U.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>3?{allowed:!1,reason:`Maximum subagent depth (3) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){U.info(`subagent status changed`,t);return}if(e.status===`killed`){U.warn(`subagent status changed`,t);return}U.error(`subagent status changed`,t)}};const Kt=new Map;function qt(e){let t=Kt.get(e);return t||(t={},Kt.set(e,t)),t}function Jt(e){Kt.delete(e)}var W=class extends Error{code;statusCode;statusText;providerMessage;providerCode;providerType;retryable;constructor(e){super(e.message,{cause:e.cause}),this.name=`LlmRequestError`,this.code=e.code,this.statusCode=e.statusCode,this.statusText=e.statusText,this.providerMessage=e.providerMessage,this.providerCode=e.providerCode,this.providerType=e.providerType,this.retryable=e.retryable}};function Yt(e){return{async chat(t){let n=Xt(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await $t(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:Zt(n),historyMessages:n},e.hookCtx);let i={model:r,messages:n,stream:!1};typeof t.temperature==`number`&&(i.temperature=t.temperature),typeof t.maxTokens==`number`&&(i.max_tokens=t.maxTokens);let{signal:a,clear:o,didTimeout:s}=en(t.signal,t.timeoutMs);try{let t;try{let n=e.baseUrl.replace(/\/$/,``);t=await fetch(`${n}/chat/completions`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:JSON.stringify(i),signal:a})}catch(e){throw nn(e,s())}if(!t.ok){let e=await tn(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new W({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:an(t.status)})}let n=Date.now(),o;try{o=await t.json()}catch(e){throw new W({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}let c=o.choices?.[0]?.message?.content??o.choices?.[0]?.text??``,l=Qt(o.usage),u=Math.max(0,Date.now()-n);return await $t(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:c?[c]:[],durationMs:u,usage:l},e.hookCtx),{text:c,usage:l,raw:o}}finally{o()}}}}function Xt(e){if(Array.isArray(e.messages)&&e.messages.length>0)return e.messages;let t=[];if(e.system?.trim()&&t.push({role:`system`,content:e.system}),e.user?.trim()&&t.push({role:`user`,content:e.user}),t.length===0)throw Error(`LLM messages are required`);return t}function Zt(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
6
+ `)}\n</available_skills>`}const mt=`/aimax/agents`,ht=/^[a-z]+(?:-[a-z]+)*$/;function gt(e){let t=[{dir:e.systemAgentsDir??mt,source:`system`},{dir:B.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:B.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function _t(e){let t=new Map;for(let n of gt(e)){let e=await vt(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}async function vt(e,t){let n;try{n=await z.readdir(e,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}let r=[];for(let i of n){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let n=B.join(e,i.name),a=yt(await z.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function yt(e,t){let n=be(e),r=Tt(n.data.name)?.trim(),i=Tt(n.data.description)?.trim();if(!r||!ht.test(r)||!i)return;let a=Tt(n.data.model)?.trim(),o=Tt(n.data.initPrompt)?.trim()??Tt(n.data.initialPrompt)?.trim(),s=Et(n.data.maxTurns),c=Dt(n.data.tools),l=Dt(n.data.disallowedTools),u=Dt(n.data.skills);return{name:r,description:i,...c?{tools:c}:{},...l?{disallowedTools:l}:{},...a&&a!==`inherit`?{model:a}:{},...s?{maxTurns:s}:{},...o?{initPrompt:o}:{},...u?{skills:u}:{},systemPrompt:n.content.trim(),sourcePath:t.sourcePath,source:t.source}}function bt(e,t){let n=t?.trim();if(n)return e.find(e=>e.name===n)}function xt(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function St(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Ot)):void 0,r=new Set((t.disallowedTools??[]).map(Ot));return e.filter(e=>{let t=typeof e.name==`string`?Ot(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Ct(e){return``}function wt(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Tt(e){return typeof e==`string`?e:void 0}function Et(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Dt(e){let t;if(typeof e==`string`)t=e.split(`,`);else if(Array.isArray(e))t=e.filter(e=>typeof e==`string`);else return;let n=t.map(e=>e.trim()).filter(Boolean);return n.length>0?n:void 0}function Ot(e){let t=e.trim();return{bash:`exec`,read:`read_file`,write:`write_file`,edit:`edit_file`,multiedit:`edit_file`,glob:`list_dir`,grep:`exec`}[t.toLowerCase()]??t}function kt(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function At(e=new Date){let t=kt(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let jt=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),Mt=null;function Nt(){return At()}function Pt(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function Ft(e){return B.join(e,`.aimax`)}function It(e){return{appLogPath:B.join(e,`app.log`),errorLogPath:B.join(e,`errors.log`)}}function Lt(e){let{appLogPath:t,errorLogPath:n}=It(e);xe.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function Rt(e,t,n){return`[${Nt()}] [${e}] ${t}${Pt(n)}`}function zt(e,t,n){process.stderr.write(`${Rt(e,t,n)}\n`)}function Bt(e,t,n){if(!Mt){zt(e,t,n);return}let r=Rt(e,t,n),i=xe.getLogger();if(e===jt.ERROR){i.error(r);return}if(e===jt.WARN){i.warn(r);return}i.info(r)}function Vt(e){let t=Ft(e);Mt?.dataDir!==e&&(V.mkdirSync(t,{recursive:!0}),Lt(t),Mt={dataDir:e,logDir:t})}const U={info:(e,t)=>Bt(jt.INFO,e,t),warn:(e,t)=>Bt(jt.WARN,e,t),error:(e,t)=>Bt(jt.ERROR,e,t)};function Ht(e,t=240){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}const Ut=3,Wt=5;var Gt=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),U.info(`subagent status changed`,{runId:e.runId,status:`running`,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,taskLength:e.task.length,taskPreview:Ht(e.task),startedAt:e.startedAt})}complete(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`done`,n.record.result=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}fail(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`error`,n.record.error=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}kill(e){let t=this.entries.get(e);return!t||t.record.status!==`running`?!1:(t.record.abortController.abort(),t.record.status=`killed`,t.record.endedAt=Date.now(),this.logTerminalStatus(t.record),!0)}killAll(e){let t=0;for(let{record:n}of this.entries.values())n.parentSessionId===e&&n.status===`running`&&(n.abortController.abort(),n.status=`killed`,n.endedAt=Date.now(),this.logTerminalStatus(n),t++);return t}list(e){return Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e).map(e=>e.record)}hasPending(e){return this.list(e).some(e=>e.status===`running`)}countActive(e){return this.list(e).filter(e=>e.status===`running`).length}async waitForAll(e){let t=Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e&&t.record.status===`running`).map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}peekCompleted(e){return this.list(e).filter(e=>e.status!==`running`&&!this.announced.has(e.runId))}consumeCompleted(e){let t=this.peekCompleted(e);return this.markAnnounced(t.map(e=>e.runId)),t}markAnnounced(e){let t=Array.isArray(e)?e:[e];for(let e of t){this.announced.add(e);let t=this.entries.get(e)?.record;t&&U.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>3?{allowed:!1,reason:`Maximum subagent depth (3) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){U.info(`subagent status changed`,t);return}if(e.status===`killed`){U.warn(`subagent status changed`,t);return}U.error(`subagent status changed`,t)}};const Kt=new Map;function qt(e){let t=Kt.get(e);return t||(t={},Kt.set(e,t)),t}function Jt(e){Kt.delete(e)}var W=class extends Error{code;statusCode;statusText;providerMessage;providerCode;providerType;retryable;constructor(e){super(e.message,{cause:e.cause}),this.name=`LlmRequestError`,this.code=e.code,this.statusCode=e.statusCode,this.statusText=e.statusText,this.providerMessage=e.providerMessage,this.providerCode=e.providerCode,this.providerType=e.providerType,this.retryable=e.retryable}};function Yt(e){return{async chat(t){let n=Xt(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await $t(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:Zt(n),historyMessages:n},e.hookCtx);let i={model:r,messages:n,stream:!1};typeof t.temperature==`number`&&(i.temperature=t.temperature),typeof t.maxTokens==`number`&&(i.max_tokens=t.maxTokens);let{signal:a,clear:o,didTimeout:s}=en(t.signal,t.timeoutMs);try{let t;try{let n=e.baseUrl.replace(/\/$/,``);t=await fetch(`${n}/chat/completions`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:JSON.stringify(i),signal:a})}catch(e){throw nn(e,s())}if(!t.ok){let e=await tn(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new W({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:an(t.status)})}let n=Date.now(),o;try{o=await t.json()}catch(e){throw new W({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}let c=o.choices?.[0]?.message?.content??o.choices?.[0]?.text??``,l=Qt(o.usage),u=Math.max(0,Date.now()-n);return await $t(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:c?[c]:[],durationMs:u,usage:l},e.hookCtx),{text:c,usage:l,raw:o}}finally{o()}}}}function Xt(e){if(Array.isArray(e.messages)&&e.messages.length>0)return e.messages;let t=[];if(e.system?.trim()&&t.push({role:`system`,content:e.system}),e.user?.trim()&&t.push({role:`user`,content:e.user}),t.length===0)throw Error(`LLM messages are required`);return t}function Zt(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
9
7
  `)}function Qt(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}async function $t(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function en(e,t){if(!e&&(!t||t<=0))return{signal:void 0,clear:()=>{},didTimeout:()=>!1};let n=new AbortController,r,i=!1;return e&&(e.aborted?n.abort():e.addEventListener(`abort`,()=>n.abort(),{once:!0})),t&&t>0&&(r=setTimeout(()=>{i=!0,n.abort()},t)),{signal:n.signal,clear:()=>{r&&clearTimeout(r)},didTimeout:()=>i}}async function tn(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function nn(e,t){return e instanceof W?e:rn(e)?t?new W({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new W({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function rn(e){return e instanceof Error&&e.name===`AbortError`}function an(e){return e===408||e===409||e===425||e===429||e>=500}function on(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function sn(e){if(!on(e))return null;let t=e,n=cn(t.message),r=G(n?.code)??G(t.code),i=G(n?.type)??G(t.type),a=G(n?.message)??ln(t.error)??G(t.message)??`Unknown upstream error`;return{message:un(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:dn(r,i),raw:e}}function cn(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return null;try{let e=JSON.parse(t);return e&&typeof e==`object`?e:null}catch{return null}}function ln(e){if(!(!e||typeof e!=`object`))return G(e.message)}function G(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function un(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function dn(e,t){let n=Number(e);if(Number.isFinite(n))return n===408||n===409||n===425||n===429||n>=500;let r=t?.toLowerCase();return r===`ratelimiterror`||r===`internalservererror`}const fn=(e,t,n)=>{let r=new ke;return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now(),errorMessage:void 0};try{let a=mn(e,t,n?.apiKey||Ce(e.provider)||``,n?.headers),o=hn(e,t,n);n?.onPayload?.(o);let s=await a.chat.completions.create(o,{signal:n?.signal});r.push({type:`start`,partial:i});let c=null,l=i.content,u=()=>l.length-1,d=e=>{if(e){if(e.type===`text`){r.push({type:`text_end`,contentIndex:u(),content:e.text,partial:i});return}if(e.type===`thinking`){r.push({type:`thinking_end`,contentIndex:u(),content:e.thinking,partial:i});return}e.type===`toolCall`&&(e.arguments=we(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=sn(t);if(n)throw new W({message:`LLM upstream returned an error payload in a 200 stream: ${n.message}`,code:`stream_payload_error`,providerMessage:n.providerMessage,providerCode:n.providerCode,providerType:n.providerType,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Se(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=xn(a.finish_reason)),!a.delta))continue;a.delta.content!==null&&a.delta.content!==void 0&&a.delta.content.length>0&&((!c||c.type!==`text`)&&(d(c),c={type:`text`,text:``},i.content.push(c),r.push({type:`text_start`,contentIndex:u(),partial:i})),c.text+=a.delta.content,r.push({type:`text_delta`,contentIndex:u(),delta:a.delta.content,partial:i}));let o=[`reasoning_content`,`reasoning`,`reasoning_text`].find(e=>{let t=a.delta[e];return t!=null&&t.length>0});if(o){(!c||c.type!==`thinking`)&&(d(c),c={type:`thinking`,thinking:``,thinkingSignature:o},i.content.push(c),r.push({type:`thinking_start`,contentIndex:u(),partial:i}));let e=a.delta[o];c.thinking+=e,r.push({type:`thinking_delta`,contentIndex:u(),delta:e,partial:i})}if(a.delta.tool_calls)for(let e of a.delta.tool_calls){(!c||c.type!==`toolCall`||e.id&&c.id!==e.id)&&(d(c),c={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``},i.content.push(c),r.push({type:`toolcall_start`,contentIndex:u(),partial:i})),e.id&&(c.id=e.id),e.function?.name&&(c.name=e.function.name);let t=``;e.function?.arguments&&(t=e.function.arguments,c.partialArgs+=e.function.arguments,c.arguments=we(c.partialArgs)),r.push({type:`toolcall_delta`,contentIndex:u(),delta:t,partial:i})}let s=a.delta.reasoning_details;if(s&&Array.isArray(s)){for(let e of s)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=i.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}if(d(c),n?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(i.errorMessage??(i.stopReason===`aborted`?`Request was aborted`:`LLM stream ended with stopReason=${i.stopReason}`));r.push({type:`done`,reason:i.stopReason,message:i}),r.end()}catch(e){for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`,i.errorMessage=e instanceof Error?e.message:JSON.stringify(e),e instanceof W&&Object.assign(i,{errorCode:e.code,statusCode:e.statusCode,statusText:e.statusText,providerMessage:e.providerMessage,providerCode:e.providerCode,providerType:e.providerType,retryable:e.retryable});let t=e?.error?.metadata?.raw;t&&(i.errorMessage+=`\n${t}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},pn=(e,t,n)=>{let r=n?.apiKey||Ce(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Ne(e,n,r),a=De(e)?n?.reasoning:Pe(n?.reasoning);return fn(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function mn(e,t,n,r){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let i={...e.headers};if(e.provider===`github-copilot`){let e=Me(t.messages);Object.assign(i,je({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new Oe({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function hn(e,t,n){let r=Cn(e),i=yn(e,t,r);vn(e,i);let a={model:e.id,messages:i,stream:!0};if(r.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),r.supportsStore&&(a.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?a.max_tokens=n.maxTokens:a.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(a.temperature=n.temperature),t.tools?a.tools=bn(t.tools,r):gn(t.messages)&&(a.tools=[]),n?.toolChoice&&(a.tool_choice=n.toolChoice),(r.thinkingFormat===`zai`||r.thinkingFormat===`qwen`)&&e.reasoning?a.enable_thinking=!!n?.reasoningEffort:n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort&&(a.reasoning_effort=n.reasoningEffort),e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),a.providerOptions={gateway:e}}}return a}function gn(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function _n(e){let t=e.replace(/[^a-zA-Z0-9]/g,``);return t.length<9?t+=`ABCDEFGHI`.slice(0,9-t.length):t.length>9&&(t=t.slice(0,9)),t}function vn(e,t){if(!(e.provider!==`openrouter`||!e.id.startsWith(`anthropic/`)))for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.role!==`user`&&n.role!==`assistant`)continue;let r=n.content;if(typeof r==`string`){n.content=[{type:`text`,text:r,cache_control:{type:`ephemeral`}}];return}if(Array.isArray(r))for(let e=r.length-1;e>=0;--e){let t=r[e];if(t?.type===`text`){Object.assign(t,{cache_control:{type:`ephemeral`}});return}}}}function yn(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return _n(t);if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=Fe(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:Ae(t.systemPrompt)})}let o=null;for(let t=0;t<a.length;t+=1){let i=a[t];if(n.requiresAssistantAfterToolResult&&o===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`){if(typeof i.content==`string`)r.push({role:`user`,content:Ae(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:Ae(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}),n=e.input.includes(`image`)?t:t.filter(e=>e.type!==`image_url`);if(n.length===0)continue;r.push({role:`user`,content:n})}o=i.role;continue}if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(e=>e.type===`text`&&e.text?.trim().length>0);a.length>0&&(t.content=e.provider===`github-copilot`?a.map(e=>Ae(e.text)).join(``):a.map(e=>({type:`text`,text:Ae(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
10
8
 
11
9
  `);t.content?t.content.unshift({type:`text`,text:e}):t.content=[{type:`text`,text:e}]}else{let e=s[0].thinkingSignature;e&&e.length>0&&(t[e]=s.map(e=>e.thinking).join(`
@@ -68,7 +66,7 @@ import{A as e,C as t,D as n,E as r,M as i,N as a,O as o,P as s,S as c,T as l,_ a
68
66
  `),t.line);return a===null?{content:[{type:`text`,text:`Line ${t.line} out of range in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Q(e,t.filePath,a,i),{content:[{type:`text`,text:`Forgotten line ${t.line} from ${t.filePath}`}],details:{removed:1,id:r.id}})}return r.id===`MEMORY.md`?{content:[{type:`text`,text:`Cannot delete MEMORY.md directly. Use id with a section (e.g. MEMORY.md#SectionName) to remove individual entries, or use query mode.`}],details:{removed:0,id:r.id}}:(await _a(e,r.id,i),{content:[{type:`text`,text:`Forgotten memory: ${r.id}`}],details:{removed:1,id:r.id}})}if(r.query){let t=Math.min(Math.max(r.limit??5,1),20),n=await pa(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await _a(e,r.path,i),a+=1);return{content:[{type:`text`,text:`Forgotten ${a} memor${a===1?`y`:`ies`} matching: ${r.query}`}],details:{removed:a,query:r.query}}}return{content:[{type:`text`,text:`Provide id or query to forget memories.`}],details:{removed:0}}}catch(e){throw Error(`Failed to forget memory: ${e instanceof Error?e.message:String(e)}`)}}}}const Ra=H.Object({id:H.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:H.String({description:`New content to replace the existing memory with`})});function za(e,t){return{name:`memory_update`,label:`Update Memory`,description:`Replace an existing memory's content by its entry ID. Use memory_list or memory_search first to find the correct ID. IDs with # (e.g. MEMORY.md#Preferences) update only that section; IDs without # replace the entire file.`,parameters:Ra,async execute(n,r){try{let n=Aa(r.id);if(n.section){let i=Ea(await fa(e)??``,n.section,r.content);return await Q(e,n.filePath,i,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (section "${n.section}")`}],details:{id:r.id}}}if(n.line!==void 0){let i=await ma(e,n.filePath,1,1e4,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(!i)throw Error(`File not found: ${n.filePath}`);let a=ka(i.join(`
69
67
  `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await Q(e,n.filePath,a,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (line ${n.line})`}],details:{id:r.id}}}return await Q(e,r.id,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id}`}],details:{id:r.id}}}catch(e){throw Error(`Failed to update memory: ${e instanceof Error?e.message:String(e)}`)}}}}const Ba=H.Object({query:H.Optional(H.String({description:`Search query; omit to browse recent sessions.`})),role_filter:H.Optional(H.Union([H.Literal(`user`),H.Literal(`assistant`),H.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:H.Optional(H.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:H.Optional(H.Union([H.Literal(`llm`),H.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function Va(e,n){return{name:`session_search`,label:`Session Search`,description:`Search past conversation transcripts across sessions for cross-session recall. Use when the user asks about what was discussed, decided, or done in previous chats (e.g. last time, before, remember when). Omit query to browse recent sessions with zero LLM cost; include query to search transcripts and return summaries. Do not use this as the only source for stable project policy/config if long-term memory docs exist (use memory_search for durable docs).`,parameters:Ba,async execute(r,i){let a=Ha(i.limit),o=i.summary_mode??`llm`,s=i.query?.trim(),c=i.role_filter;if(!s){let t=await Ua(e,a,n),r={mode:`recent`,count:t.length,results:t};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let l=await Wa({dataDir:e,query:s,roleFilter:c,messageLimit:50,sessionLimit:a,currentSessionId:n?.sessionId,sessionStoreName:n?.sessionStoreName});if(l.length===0){let e={mode:`query`,query:s,count:0,results:[]};return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}let u=[];for(let r of l){let i=ro(s,r.snippets);if(o===`off`){u.push({session_id:r.sessionId,summary:i,when:r.when,source:r.source,meta:{summary_source:`extractive`,snippet:r.snippets[0],score:Number(r.score.toFixed(4))}});continue}if(!n?.llm){u.push({session_id:r.sessionId,summary:i,when:r.when,source:r.source,meta:{summary_source:`extractive_short_circuit`,snippet:r.snippets[0],score:Number(r.score.toFixed(4)),summary_error:`llm configuration unavailable`}});continue}try{let a=await tr({entries:eo($a(await t(e,r.sessionId,{storeName:n?.sessionStoreName})),s,1e5),llm:n.llm,instructions:no({query:s})});u.push({session_id:r.sessionId,summary:a.trim()||i,when:r.when,source:r.source,meta:{summary_source:`llm`,snippet:r.snippets[0],score:Number(r.score.toFixed(4))}})}catch(e){u.push({session_id:r.sessionId,summary:i,when:r.when,source:r.source,meta:{summary_source:`llm_fallback_extractive`,snippet:r.snippets[0],score:Number(r.score.toFixed(4)),summary_error:e instanceof Error?e.message:String(e)}})}}let d={mode:`query`,query:s,count:u.length,results:u};return{content:[{type:`text`,text:JSON.stringify(d,null,2)}],details:d}}}}function Ha(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Ua(e,t,n){let r=await j(e,{storeName:n?.sessionStoreName}),i=[];for(let t of r){if(t===n?.sessionId)continue;let r=await c(e,t,{storeName:n?.sessionStoreName});r&&i.push({id:t,when:r.updatedAt||r.createdAt||``,source:r.channel??`unknown`,title:r.title?.trim()||`Session activity summary unavailable.`})}return i.sort((e,t)=>t.when.localeCompare(e.when)),i.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function Wa(e){let t=e.messageLimit??50,n=(await j(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Ja(e.query),i=(await io(n,6,async t=>Ga({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Qa).slice(0,t);if(i.length===0)return[];let a=new Map;for(let e of i){let t=a.get(e.sessionId)??{sessionId:e.sessionId,score:0,snippets:[],matchedMessageCount:0,when:e.timestamp||``,source:`unknown`};t.score+=e.score,t.matchedMessageCount+=1,t.snippets.length<3&&!t.snippets.includes(e.snippet)&&t.snippets.push(e.snippet),e.timestamp&&e.timestamp>t.when&&(t.when=e.timestamp),a.set(e.sessionId,t)}let o=Array.from(a.values());for(let t of o){let n=await c(e.dataDir,t.sessionId,{storeName:e.sessionStoreName});n&&(t.when=n.updatedAt||n.createdAt||t.when,t.source=n.channel??`unknown`)}return o.sort((e,t)=>t.score===e.score?t.when.localeCompare(e.when):t.score-e.score),o.slice(0,e.sessionLimit)}async function Ga(e){let t=a(e.dataDir,e.sessionId,{storeName:e.storeName});if(!V.existsSync(t))return[];let n=[],r=V.createReadStream(t,{encoding:`utf-8`}),i=He.createInterface({input:r,crlfDelay:1/0});try{for await(let t of i){let r=t.trim();if(!r||!Ka(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!qa(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Xa(i.content,e.terms,i.role);if(a<=0)continue;let o=Za(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(Qa),n.length=20)}}finally{i.close(),r.destroy()}return n.sort(Qa),n}function Ka(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function qa(e){return e===`user`||e===`assistant`||e===`tool_result`}function Ja(e){let t=e.toLowerCase().trim(),n=new Set;t.length>0&&n.add(t);let r=t.match(/[\p{L}\p{N}_-]+/gu)??[];for(let e of r)e.length>=2&&n.add(e);let i=Array.from(t).filter(e=>Ya(e)).join(``);if(i.length>=2)for(let e=0;e<=i.length-2;e+=1)n.add(i.slice(e,e+2));return Array.from(n).slice(0,30)}function Ya(e){let t=e.codePointAt(0)??0;return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=12352&&t<=12543||t>=44032&&t<=55215}function Xa(e,t,n){let r=e.toLowerCase(),i=0;for(let e of t)e&&r.includes(e)&&(i+=1);if(i===0)return 0;let a=n===`user`?1.2:n===`assistant`?1:.7;return i*i*a}function Za(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Qa(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function $a(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function eo(e,t,n){if(e.length===0)return e;let r=Ja(t);if(e.reduce((e,t)=>e+t.content.length,0)<=n)return e;let i=[];for(let t=0;t<e.length;t+=1){let n=e[t].content.toLowerCase();r.some(e=>e&&n.includes(e))&&i.push(t)}if(i.length===0)return to(e,n);let a=i[0],o=i[0],s=e[a].content.length;for(;s<n&&(a>0||o<e.length-1);){if(o<e.length-1){let t=e[o+1].content.length;if(s+t<=n)o+=1,s+=t;else break}if(a>0){let t=e[a-1].content.length;if(s+t<=n)--a,s+=t;else break}}return e.slice(a,o+1)}function to(e,t){let n=[],r=0;for(let i=e.length-1;i>=0;--i){let a=e[i];if(r+a.content.length>t)break;n.push(a),r+=a.content.length}return n.reverse()}function no(e){let t=e.languageHint?.trim(),n=[`Summarize this past session for retrieval use.`,`Focus query: ${e.query}`,`Prioritize: final outcome, key actions, concrete evidence (files/commands/ids), unresolved items.`,`Do not invent facts. If evidence is missing, say so explicitly.`,`Keep it concise and factual.`];return t&&n.push(`Respond in: ${t}`),n.join(`
70
68
  `)}function ro(e,t){return t.length===0?`No direct transcript snippet was extracted for query: ${e}`:`Extractive summary for "${e}":\n${t.slice(0,3).map((e,t)=>`${t+1}. ${e}`).join(`
71
- `)}`}async function io(e,t,n){if(e.length===0)return[];let r=Math.max(1,Math.trunc(t)),i=Array(e.length),a=0,o=Array(Math.min(r,e.length)).fill(0).map(async()=>{for(;;){let t=a;if(a+=1,t>=e.length)break;i[t]=await n(e[t])}});return await Promise.all(o),i}const ao=H.Object({category:H.Optional(H.String({description:`Reserved category filter field. Not used yet.`}))}),oo=H.Object({name:H.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:H.Optional(H.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function so(e,t,n=[]){return[...n,...t,rt(e)]}function co(e,t,n=[]){let r=so(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:ao,async execute(e,t){let n=await lt(r),i={skills:n.map(e=>({name:e.name,description:e.description})),count:n.length};return{content:[{type:`text`,text:JSON.stringify({success:!0,...i,hint:`Use skill_load(name) to load the skill's SKILL.md entrypoint.`})}],details:i}}}}function lo(e){let t=so(e.dataDir,e.pluginDirs,e.skillsLoadPaths),n=new Set;return{name:`skill_load`,label:`Skill Load`,description:`Load a skill's SKILL.md entrypoint. Optionally override lookup with skillPath.`,parameters:oo,async execute(r,i){let a=await ft(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``}}}}}const uo=H.Object({task:H.String({description:`The task description for the subagent to execute`}),label:H.Optional(H.String({description:`Optional short label to identify this subagent`})),agent:H.Optional(H.String({description:`Optional custom agent name to use for this subagent`}))});function fo(e){let t=e.label?`"${e.label}"`:`task: ${me(e.task)}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${po(e.result??`(no output)`)}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function po(e){let t=e.trim().match(/^\[Subagent (?:completed|failed|killed)\][^\n]*(?:\n\n([\s\S]*))?$/);return t?t[1]?.trim()||`(no output)`:e}function mo(e,t,n,r,i,a,o,s,c){return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. Do not use it for routine decomposition or inferred parallelism — only when the user or system instructions explicitly require subagent delegation or parallel agent execution. Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:uo,async execute(l,u){let d=u.task.trim(),f=u.label?.trim(),p=u.agent?.trim();if(U.info(`subagent spawn requested`,{parentSessionId:t,depth:n+1,label:f,requestedAgentName:p,taskLength:d.length,taskPreview:Ht(d)}),!d){let e={status:`error`,error:`task must not be empty`};return U.warn(`subagent spawn rejected`,{parentSessionId:t,depth:n+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let m=e.checkSpawnAllowed(t,n+1);if(!m.allowed){let e={status:`forbidden`,error:m.reason};return U.warn(`subagent spawn rejected`,{parentSessionId:t,depth:n+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let h=Le(),g=new AbortController,_=l,v=bt(s.agentPolicy?.availableAgents??[],p);if(p&&!v){let e={status:`error`,error:`Unknown custom agent: ${p}`};return U.warn(`subagent spawn rejected`,{parentSessionId:t,depth:n+1,requestedAgentName:p,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}try{await T(r,i,{storeName:s.sessionStoreName,subagent:{parentSessionId:t},sessionId:_})}catch(e){let r={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return U.error(`subagent session creation failed`,{parentSessionId:t,depth:n+1,error:r.error}),{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}U.info(`subagent session created`,{parentSessionId:t,childSessionId:_,depth:n+1,runId:h,requestedAgentName:p,selectedAgent:v?.name});let y={runId:h,childSessionId:_,parentSessionId:t,task:d,label:f,depth:n+1,status:`running`,startedAt:Date.now(),abortController:g};await s.onProgress?.({type:`subagent_spawn`,childSessionId:_,task:d,label:f,sessionId:t,messageId:s.messageId,depth:n+1});let b=c({dataDir:r,sessionId:_,message:v?wt(v,d):d,channel:i,llm:v?.model?{...a,model:v.model}:a,...s,agentPolicy:{availableAgents:s.agentPolicy?.availableAgents??[],...v?{activeAgent:v}:{}},loopDetection:o,abortSignal:g.signal,sessionPathScope:{subagent:{parentSessionId:t}},subagentContext:{depth:n+1,parentSessionId:t}}).then(t=>{e.complete(h,t.text||t.error||`(no output)`)}).catch(t=>{let n=t instanceof Error?t.message:String(t);e.fail(h,n)});e.register(y,b),U.info(`subagent run registered`,{runId:h,parentSessionId:t,childSessionId:_,depth:n+1,selectedAgent:v?.name}),await b,U.info(`subagent run settled`,{runId:h,parentSessionId:t,childSessionId:_,status:y.status,durationMs:y.endedAt?y.endedAt-y.startedAt:void 0,hasError:!!y.error}),e.markAnnounced(h),await s.onProgress?.({type:`subagent_complete`,childSessionId:_,task:d,status:y.status,sessionId:t,messageId:s.messageId,depth:n+1});let x=fo({task:d,label:f,status:y.status,result:y.result,error:y.error});if(y.status===`done`){let e={status:`done`,childSessionId:_,runId:h,result:y.result??``};return U.info(`subagent spawn completed`,{runId:h,parentSessionId:t,childSessionId:_,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:x}],details:e}}let S=y.status===`killed`?{status:`killed`,childSessionId:_,runId:h,error:`subagent killed`}:{status:`error`,childSessionId:_,runId:h,error:y.error??`unknown error`};return U.warn(`subagent spawn completed with non-success status`,{runId:h,parentSessionId:t,childSessionId:_,status:S.status,error:S.error}),{content:[{type:`text`,text:x}],details:S}}}}const ho=H.Object({action:H.Union([`list`,`kill`].map(e=>H.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:H.Optional(H.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function go(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m${Math.floor(e%6e4/1e3)}s`}function _o(e,t){let n=parseInt(t,10);return!isNaN(n)&&n>=1&&n<=e.length?e[n-1]:e.find(e=>e.runId.startsWith(t)||e.runId===t)||(e.find(e=>e.label&&e.label.toLowerCase()===t.toLowerCase())??null)}function vo(e,t){return{name:`subagents`,label:`Subagents`,description:`List or kill subagents spawned by this session. Use list to check status, kill to stop one or all.`,parameters:ho,async execute(n,r){let i=r.action,a=Date.now(),o=e.list(t);if(i===`list`){let t=o.map((t,n)=>{let r=t.status===`running`?`running`:e.isAnnounced(t.runId)?`delivered`:`pending`;return{index:n+1,runId:t.runId,label:t.label??t.task.slice(0,40),task:t.task,status:t.status,deliveryStatus:r,depth:t.depth,runtimeMs:t.endedAt?t.endedAt-t.startedAt:a-t.startedAt,...t.result===void 0?{}:{result:t.result},...t.error===void 0?{}:{error:t.error}}}),n={action:`list`,runs:t,text:(t.length===0?[`(no subagents)`]:t.map(e=>{let t=e.deliveryStatus===`running`?``:`, ${e.deliveryStatus}`,n=e.result===void 0?e.error===void 0?``:`\n error: ${e.error}`:`\n result: ${e.result}`;return`${e.index}. [${e.status}${t}] ${e.label} (${go(e.runtimeMs)})${n}`})).join(`
69
+ `)}`}async function io(e,t,n){if(e.length===0)return[];let r=Math.max(1,Math.trunc(t)),i=Array(e.length),a=0,o=Array(Math.min(r,e.length)).fill(0).map(async()=>{for(;;){let t=a;if(a+=1,t>=e.length)break;i[t]=await n(e[t])}});return await Promise.all(o),i}const ao=H.Object({category:H.Optional(H.String({description:`Reserved category filter field. Not used yet.`}))}),oo=H.Object({name:H.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:H.Optional(H.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function so(e,t,n=[]){return[...n,...t,rt(e)]}function co(e,t,n=[]){let r=so(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:ao,async execute(e,t){let n=await lt(r),i={skills:n.map(e=>({name:e.name,description:e.description})),count:n.length};return{content:[{type:`text`,text:JSON.stringify({success:!0,...i,hint:`Use skill_load(name) to load the skill's SKILL.md entrypoint.`})}],details:i}}}}function lo(e){let t=so(e.dataDir,e.pluginDirs,e.skillsLoadPaths),n=new Set;return{name:`skill_load`,label:`Skill Load`,description:`Load a skill's SKILL.md entrypoint. Optionally override lookup with skillPath.`,parameters:oo,async execute(r,i){let a=await ft(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``}}}}}const uo=H.Object({task:H.String({description:`The task description for the subagent to execute`}),label:H.Optional(H.String({description:`Optional short label to identify this subagent`}))});function fo(e){let t=e.label?`"${e.label}"`:`task: ${me(e.task)}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${po(e.result??`(no output)`)}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function po(e){let t=e.trim().match(/^\[Subagent (?:completed|failed|killed)\][^\n]*(?:\n\n([\s\S]*))?$/);return t?t[1]?.trim()||`(no output)`:e}function mo(e,t,n,r,i,a,o,s,c){return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. Do not use it for routine decomposition or inferred parallelism — only when the user or system instructions explicitly require subagent delegation or parallel agent execution. Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:uo,async execute(l,u){let d=u.task.trim(),f=u.label?.trim();if(U.info(`subagent spawn requested`,{parentSessionId:t,depth:n+1,label:f,taskLength:d.length,taskPreview:Ht(d)}),!d){let e={status:`error`,error:`task must not be empty`};return U.warn(`subagent spawn rejected`,{parentSessionId:t,depth:n+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let p=e.checkSpawnAllowed(t,n+1);if(!p.allowed){let e={status:`forbidden`,error:p.reason};return U.warn(`subagent spawn rejected`,{parentSessionId:t,depth:n+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let m=Le(),h=new AbortController,g=l;try{await T(r,i,{storeName:s.sessionStoreName,subagent:{parentSessionId:t},sessionId:g})}catch(e){let r={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return U.error(`subagent session creation failed`,{parentSessionId:t,depth:n+1,error:r.error}),{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}U.info(`subagent session created`,{parentSessionId:t,childSessionId:g,depth:n+1,runId:m});let _={runId:m,childSessionId:g,parentSessionId:t,task:d,label:f,depth:n+1,status:`running`,startedAt:Date.now(),abortController:h};await s.onProgress?.({type:`subagent_spawn`,childSessionId:g,task:d,label:f,sessionId:t,messageId:s.messageId,depth:n+1});let v=c({dataDir:r,sessionId:g,message:d,channel:i,llm:a,...s,agentPolicy:{availableAgents:s.agentPolicy?.availableAgents??[]},loopDetection:o,abortSignal:h.signal,sessionPathScope:{subagent:{parentSessionId:t}},subagentContext:{depth:n+1,parentSessionId:t}}).then(t=>{if(t.error){e.fail(m,t.error);return}e.complete(m,t.text||`(no output)`)}).catch(t=>{let n=t instanceof Error?t.message:String(t);e.fail(m,n)});e.register(_,v),U.info(`subagent run registered`,{runId:m,parentSessionId:t,childSessionId:g,depth:n+1}),await v,U.info(`subagent run settled`,{runId:m,parentSessionId:t,childSessionId:g,status:_.status,durationMs:_.endedAt?_.endedAt-_.startedAt:void 0,hasError:!!_.error}),e.markAnnounced(m),await s.onProgress?.({type:`subagent_complete`,childSessionId:g,task:d,status:_.status,sessionId:t,messageId:s.messageId,depth:n+1});let y=fo({task:d,label:f,status:_.status,result:_.result,error:_.error});if(_.status===`done`){let e={status:`done`,childSessionId:g,runId:m,result:_.result??``};return U.info(`subagent spawn completed`,{runId:m,parentSessionId:t,childSessionId:g,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:y}],details:e}}let b=_.status===`killed`?{status:`killed`,childSessionId:g,runId:m,error:`subagent killed`}:{status:`error`,childSessionId:g,runId:m,error:_.error??`unknown error`};return U.warn(`subagent spawn completed with non-success status`,{runId:m,parentSessionId:t,childSessionId:g,status:b.status,error:b.error}),{content:[{type:`text`,text:y}],isError:!0,details:b}}}}const ho=H.Object({action:H.Union([`list`,`kill`].map(e=>H.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:H.Optional(H.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function go(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m${Math.floor(e%6e4/1e3)}s`}function _o(e,t){let n=parseInt(t,10);return!isNaN(n)&&n>=1&&n<=e.length?e[n-1]:e.find(e=>e.runId.startsWith(t)||e.runId===t)||(e.find(e=>e.label&&e.label.toLowerCase()===t.toLowerCase())??null)}function vo(e,t){return{name:`subagents`,label:`Subagents`,description:`List or kill subagents spawned by this session. Use list to check status, kill to stop one or all.`,parameters:ho,async execute(n,r){let i=r.action,a=Date.now(),o=e.list(t);if(i===`list`){let t=o.map((t,n)=>{let r=t.status===`running`?`running`:e.isAnnounced(t.runId)?`delivered`:`pending`;return{index:n+1,runId:t.runId,label:t.label??t.task.slice(0,40),task:t.task,status:t.status,deliveryStatus:r,depth:t.depth,runtimeMs:t.endedAt?t.endedAt-t.startedAt:a-t.startedAt,...t.result===void 0?{}:{result:t.result},...t.error===void 0?{}:{error:t.error}}}),n={action:`list`,runs:t,text:(t.length===0?[`(no subagents)`]:t.map(e=>{let t=e.deliveryStatus===`running`?``:`, ${e.deliveryStatus}`,n=e.result===void 0?e.error===void 0?``:`\n error: ${e.error}`:`\n result: ${e.result}`;return`${e.index}. [${e.status}${t}] ${e.label} (${go(e.runtimeMs)})${n}`})).join(`
72
70
  `)};return{content:[{type:`text`,text:JSON.stringify(n)}],details:n}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=_o(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}const yo=H.Object({image:H.String({description:`Image path or URL`}),prompt:H.Optional(H.String({description:`Prompt for image analysis`})),model:H.Optional(H.String({description:`Optional model override`})),maxBytesMb:H.Optional(H.Number({description:`Optional size cap in MB`}))});function bo(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:yo,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}var xo=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,outputSchema:i,extra:a,createdAt:new Date().toISOString()}}};function So(e){return!!(e instanceof xo||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const Co=new Ue;function wo(){return{}}async function To(e,t){return await Co.run(e,t)}function Eo(e){let t=Co.getStore();!t||t.signal||(t.signal=e)}const Do=H.Object({reason:H.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Oo(e){let{name:t,label:n,description:r,sessionId:i,inputSchema:a,outputSchema:o,extra:s,validate:c,resume:l}=e;return{name:t,label:n,description:r,parameters:a??Do,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=_e(o,l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(c){let e=await c(l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:l.values})}],details:{}}}let r=new xo(e,i,t,e,o,s,n);throw Eo(r),r}}}function ko(e,t){let n=B.join(e,`workspace`),r=t?.memoryOptions,i=ji(),a=[vi({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),Si({registry:i,scopeKey:n}),Li(n,t?.contextManager),zi(n,t?.contextManager),Vi(n,t?.contextManager),Ui(n),Yi(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume}),ya(e,r),Va(e,r),xa(e,r),Ta(e,r),Na(e,r),Fa(e,r),La(e,r),za(e,r),co(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),lo({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return t&&a.push(mo(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),vo(t.registry,t.parentSessionId)),a}const Ao={read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,memory_search:`Search durable Markdown memory (MEMORY.md, memory/ logs) for stable facts and policies; not for cross-session chat timelines (use session_search for transcripts).`,memory_get:`Fetch a specific memory entry's content by its ID`,memory_write:`Write or update a section in long-term memory (MEMORY.md). Omit section for flat append.`,memory_log:`Append a timestamped note to today's daily log`,memory_list:`List all stored memories`,memory_forget:`Delete a specific memory by its ID, or delete matching memories by query`,memory_update:`Update the content of an existing memory by its ID`,session_search:`Search past conversation transcripts across sessions (recent browse or keyword query). For cross-session recall; use memory_search for durable docs and policies.`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},jo=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`skill_list`,`skill_load`,`memory_search`,`memory_get`,`memory_write`,`memory_log`,`memory_list`,`memory_forget`,`memory_update`,`session_search`,`subagent_spawn`,`subagents`];function Mo(e){let t=new Map;for(let n of e){let e=n.trim();if(!e)continue;let r=e.toLowerCase();t.has(r)||t.set(r,e)}let n=Array.from(t.keys());return{ordered:[...jo.filter(e=>t.has(e)),...n.filter(e=>!jo.includes(e)).sort()],displayName:t}}function No(e){let{ordered:t,displayName:n}=Mo(e.toolNames),r=new Map;for(let[t,n]of Object.entries(e.toolSummaries??{})){let e=t.trim().toLowerCase();!e||!n?.trim()||r.set(e,n.trim())}return[`## Tooling`,`Tool availability (filtered by runtime policy):`,`Tool names are case-sensitive. Call tools exactly as listed.`,t.map(e=>{let t=n.get(e)??e,i=r.get(e)??Ao[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
73
71
  `),``].join(`
74
72
  `)}function Po(){return[`## Safety`,`You have no independent goals: do not pursue self-preservation, replication, resource acquisition, or power-seeking; avoid long-term plans beyond the user's request.`,`Prioritize safety and human oversight over completion; if instructions conflict, pause and ask; comply with stop/pause/audit requests and never bypass safeguards.`,`Do not attempt to bypass approvals, safety rails, or access boundaries.`,`Never print, reveal, or echo environment variable values. If configuration must be shown, use placeholders plus brief meanings instead, such as {{API_KEY}}: model access credential.`,``].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/agents",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -32,7 +32,7 @@
32
32
  "openai": "6.10.0",
33
33
  "sqlite-vec": "^0.1.6",
34
34
  "zod": "^4.3.6",
35
- "@gencode/shared": "0.1.1"
35
+ "@gencode/shared": "0.1.2"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@sinclair/typebox": "^0.34.48",