@gencode/agents 0.0.19 → 0.0.21

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.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -31,7 +31,7 @@ import{C as e,E as t,S as n,T as r,_ as i,a,b as o,c as s,d as c,f as l,g as u,h
31
31
  `)}function mr(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function hr(e){let t=mr(e.stdout),n=e.stderr.trim();if(e.exitCode!==void 0&&e.exitCode!==0){let t=`Exit code: ${e.exitCode===null?`null`:e.exitCode}`;n=n.length>0?`${n}\n${t}`:t}return[t.length>0?t:`(no output)`,n,e.backgroundInfo?.trim()||``].filter(e=>e.length>0)}function gr(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands with optional background continuation. Use process tool to poll logs and status.`,parameters:sr,async execute(t,n,r){if(!n.command?.trim())return{content:[{type:`text`,text:`Error: command is required.`}],details:{status:`failed`}};let i;try{i=dr(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=lr(n.timeout),o=e.registry.start({command:n.command,cwd:i,env:n.env,timeoutSec:a,scopeKey:e.scopeKey}),s=n.background===!0,c=typeof n.yieldMs==`number`&&Number.isFinite(n.yieldMs),l=o,u;try{if(!s&&r&&(u=()=>{e.registry.terminate(o.sessionId,e.scopeKey)},r.aborted?u():r.addEventListener(`abort`,u,{once:!0})),!s&&!c){let t=await e.registry.wait(o.sessionId,e.scopeKey,void 0);t&&(l=t)}else if(!s){let t=await e.registry.wait(o.sessionId,e.scopeKey,ur(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:fr(l)}],details:{status:`running`,sessionId:l.sessionId,command:l.command,cwd:l.cwd,pid:l.pid}};let d=e.registry.readOutput(l.sessionId,e.scopeKey),f=d?hr({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[pr(l)],p=mr(d?.stdout??l.stdoutTail),m=await e.contextManager?.persistToolResult({toolCallId:t,toolName:`exec`,content:p.length>0?p:`(no output)`});return{content:[{type:`text`,text:[m?.content??(p.length>0?p:`(no output)`),...f.slice(1)].join(`
32
32
  `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const _r=I.Object({action:I.String({description:`Process action: list | poll | log | kill`}),sessionId:I.Optional(I.String({description:`Session id for non-list actions`})),offset:I.Optional(I.Number({description:`Log line offset (0-based)`})),limit:I.Optional(I.Number({description:`Maximum lines to return`})),timeout:I.Optional(I.Number({description:`Poll wait time in milliseconds`}))});function vr(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function G(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function yr(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:_r,async execute(t,n){let r=n.action?.trim().toLowerCase();if(r===`list`){let t=e.registry.list(e.scopeKey);return{content:[{type:`text`,text:t.length===0?`No running or recent sessions.`:t.map(e=>{let t=(e.endedAt??Date.now())-e.startedAt;return`${e.sessionId} ${e.status.padEnd(9)} ${t}ms :: ${e.command}`}).join(`
33
33
  `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return G(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,vr(n.timeout));return t?{content:[{type:`text`,text:t.status===`running`?`Session ${i} is still running.`:`Session ${i} finished with status=${t.status}, exitCode=${t.exitCode??`null`}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal,aggregated:t.status!==`running`}}:G(`No session found for ${i}`)}if(r===`log`){let t=e.registry.readLog({sessionId:i,scopeKey:e.scopeKey,offset:n.offset,limit:n.limit});return t?{content:[{type:`text`,text:t.text.trim().length>0?t.text:`(no output)`}],details:{status:t.status,sessionId:i,totalLines:t.totalLines,totalChars:t.totalChars,truncated:t.truncated,exitCode:t.exitCode,exitSignal:t.exitSignal}}:G(`No session found for ${i}`)}if(r===`kill`){let t=await e.registry.terminate(i,e.scopeKey);return t?{content:[{type:`text`,text:t.status===`running`?`Termination signal sent to ${i}.`:`Session ${i} terminated with status=${t.status}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal}}:G(`No session found for ${i}`)}return G(`Unsupported action: ${n.action}`)}}}const br=2e5;function xr(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Sr(e,t){let n=e+t;return n.length<=br?{text:n,truncated:!1}:{text:n.slice(-br),truncated:!0}}function Cr(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Sr(e.output,r);e.output=i.text;let a=Sr(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function K(e){return{sessionId:e.sessionId,scopeKey:e.scopeKey,command:e.command,cwd:e.cwd,pid:typeof e.child.pid==`number`?e.child.pid:void 0,startedAt:e.startedAt,endedAt:e.endedAt,status:e.status,exitCode:e.exitCode,exitSignal:e.exitSignal,outputTail:xr(e.output),stdoutTail:xr(e.stdout),stderrTail:xr(e.stderr),outputTruncated:e.outputTruncated}}function q(e,t){return t?e.scopeKey===t:!0}function wr(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Tr(e){return e?e.split(/\r?\n/):[]}function Er(e){let t=Tr(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=wr(e.limit,n?200:Math.max(1,t.length-r)),a=(n&&t.length>200?t.slice(t.length-200):t.slice(r,r+i)).join(`
34
- `);return{sessionId:e.record.sessionId,status:e.record.status,text:a,totalLines:t.length,totalChars:e.record.output.length,truncated:e.record.outputTruncated,exitCode:e.record.exitCode,exitSignal:e.record.exitSignal}}function Dr(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Or(){let e=new Map,t=new Map,n=n=>{if(e.delete(n.sessionId),t.set(n.sessionId,n),t.size<=100)return;let r=Array.from(t.values()).sort((e,t)=>(e.endedAt??2**53-1)-(t.endedAt??2**53-1));for(;r.length>100;){let e=r.shift();if(!e)break;t.delete(e.sessionId)}},r=n=>e.get(n)??t.get(n)??null,i=(e,t)=>{e.endedAt===void 0&&(t?.(),e.endedAt=Date.now(),n(e),Dr(e))};return{start(t){let n=ke(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:Ee(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:n,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:a,resolveDone:r};e.set(o.sessionId,o),n.stdout.on(`data`,e=>Cr(o,`stdout`,e)),n.stderr.on(`data`,e=>Cr(o,`stderr`,e));let s=wr(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Cr(o,`stderr`,Buffer.from(`\n[Timed out after ${s}s]\n`)),o.child.kill(`SIGTERM`),o.killTimer=setTimeout(()=>{(o.status===`running`||o.status===`timeout`)&&o.child.kill(`SIGKILL`)},1e3))},s*1e3),n.on(`error`,e=>{i(o,()=>{o.status===`running`&&(o.status=`failed`),Cr(o,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),n.on(`close`,(e,t)=>{i(o,()=>{o.exitCode=e,o.exitSignal=t,o.status===`running`?o.status=e===0?`completed`:`failed`:o.status===`killed`&&e===0&&(o.status=`completed`)})}),K(o)},get(e,t){let n=r(e);return!n||!q(n,t)?null:K(n)},list(n){return[...e.values(),...t.values()].filter(e=>q(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>K(e))},async wait(e,t,n){let i=r(e);if(!i||!q(i,t))return null;if(i.status!==`running`)return K(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!q(a,t)?null:K(a)},readLog(e){let t=r(e.sessionId);return!t||!q(t,e.scopeKey)?null:Er({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!q(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!q(n,t))return null;if(n.status!==`running`)return K(n);n.status=`killed`,n.child.kill(`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&n.child.kill(`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?K(i):null}}}function kr(e){return gr({workspaceDir:e,registry:Or(),scopeKey:e})}const Ar=5*1024*1024,jr=2e3;function Mr(e,t){let n=F.isAbsolute(e)?F.normalize(e):F.normalize(F.join(t,e));if(!n.startsWith(t+F.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}const Nr=I.Object({path:I.String({description:`File path (relative to workspace or absolute)`}),offset:I.Optional(I.Number({description:`Line offset (1-based, default: 1)`})),limit:I.Optional(I.Number({description:`Maximum lines to read (default: 2000)`}))});function Pr(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Nr,async execute(n,r){let i;try{i=Mr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await P.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}if(o.length>Ar){let e=o.slice(0,Ar).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Ar} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let s=o.toString(`utf-8`).split(`
34
+ `);return{sessionId:e.record.sessionId,status:e.record.status,text:a,totalLines:t.length,totalChars:e.record.output.length,truncated:e.record.outputTruncated,exitCode:e.record.exitCode,exitSignal:e.record.exitSignal}}function Dr(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Or(){let e=new Map,t=new Map,n=n=>{if(e.delete(n.sessionId),t.set(n.sessionId,n),t.size<=100)return;let r=Array.from(t.values()).sort((e,t)=>(e.endedAt??2**53-1)-(t.endedAt??2**53-1));for(;r.length>100;){let e=r.shift();if(!e)break;t.delete(e.sessionId)}},r=n=>e.get(n)??t.get(n)??null,i=(e,t)=>{e.endedAt===void 0&&(t?.(),e.endedAt=Date.now(),n(e),Dr(e))};return{start(t){let n=ke(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:Ee(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:n,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:a,resolveDone:r};e.set(o.sessionId,o),n.stdout.on(`data`,e=>Cr(o,`stdout`,e)),n.stderr.on(`data`,e=>Cr(o,`stderr`,e));let s=wr(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Cr(o,`stderr`,Buffer.from(`\n[Timed out after ${s}s]\n`)),o.child.kill(`SIGTERM`),o.killTimer=setTimeout(()=>{(o.status===`running`||o.status===`timeout`)&&o.child.kill(`SIGKILL`)},1e3))},s*1e3),n.on(`error`,e=>{i(o,()=>{o.status===`running`&&(o.status=`failed`),Cr(o,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),n.on(`close`,(e,t)=>{i(o,()=>{o.exitCode=e,o.exitSignal=t,o.status===`running`?o.status=e===0?`completed`:`failed`:o.status===`killed`&&e===0&&(o.status=`completed`)})}),K(o)},get(e,t){let n=r(e);return!n||!q(n,t)?null:K(n)},list(n){return[...e.values(),...t.values()].filter(e=>q(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>K(e))},async wait(e,t,n){let i=r(e);if(!i||!q(i,t))return null;if(i.status!==`running`)return K(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!q(a,t)?null:K(a)},readLog(e){let t=r(e.sessionId);return!t||!q(t,e.scopeKey)?null:Er({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!q(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!q(n,t))return null;if(n.status!==`running`)return K(n);n.status=`killed`,n.child.kill(`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&n.child.kill(`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?K(i):null}}}function kr(e){return gr({workspaceDir:e,registry:Or(),scopeKey:e})}const Ar=5*1024*1024,jr=2e3;function Mr(e,t){return F.isAbsolute(e)?F.normalize(e):F.normalize(F.join(t,e))}const Nr=I.Object({path:I.String({description:`File path (relative to workspace or absolute)`}),offset:I.Optional(I.Number({description:`Line offset (1-based, default: 1)`})),limit:I.Optional(I.Number({description:`Maximum lines to read (default: 2000)`}))});function Pr(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Nr,async execute(n,r){let i;try{i=Mr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await P.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}if(o.length>Ar){let e=o.slice(0,Ar).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Ar} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let s=o.toString(`utf-8`).split(`
35
35
  `),c=Math.max(1,r.offset??1),l=Math.min(jr,r.limit??jr),u=s.slice(c-1,c-1+l),d=u.length<s.length-(c-1),f=u.map((e,t)=>`${(c+t).toString().padStart(4)} ${e}`).join(`
36
36
  `),p=d?`\n[...${s.length-(c-1+u.length)} more lines]`:``;return await t?.rememberRead({path:i,content:u.join(`
37
37
  `),lineCount:u.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:f+p}],details:{content:u.join(`
@@ -65,7 +65,7 @@ import{C as e,E as t,S as n,T as r,_ as i,a,b as o,c as s,d as c,f as l,g as u,h
65
65
  `):``}function Xi(e){let t=e.promptMode??`full`,n=t===`minimal`;if(t===`none`)return`You are a personal assistant running inside AiMax.`;let r=e.toolNames&&e.toolNames.length>0?e.toolNames:[...Mi],i=e.skills??[],a=e.contextFiles??[];return[`You are a personal assistant running inside AiMax.
66
66
  `,Pi({toolNames:r,toolSummaries:e.toolSummaries}),Ii(n),Fi(),Li(i),Ri(),zi(e.memoryCitationsMode??`off`),Bi({dataDir:e.dataDir,sandboxInfo:e.sandboxInfo}),Vi(e.sandboxInfo),Hi({currentDate:e.currentDate,timezone:e.timezone}),Ui({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Wi({isMinimal:n,docs:e.docs}),Ki({isMinimal:n}),qi({isMinimal:n,heartbeatPrompt:e.heartbeatPrompt}),Gi(e.runtimeInfo),Ji({contextFiles:a,bootstrapWarnings:e.bootstrapWarnings}),Yi(e.priorConversationSummary)].filter(Boolean).join(`
67
67
  `)}function Zi(e,t,n){return e.map(e=>{let r=e,i=e.name??`unknown`;return{...r,async execute(e,a,o,s){let c=Date.now(),l=a??{},u=!1,d,f=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:i,params:l},n);for(let e of f)e&&(e.params&&(l=e.params),e.block&&(u=!0,d=e.blockReason));if(u)return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:i,params:l,error:d??`blocked by plugin`,durationMs:Date.now()-c},n),{content:[{type:`text`,text:d??`Tool blocked by plugin`}],isError:!0,details:{}};try{let a=await r.execute(e,l,o,s);return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:i,params:l,result:a,durationMs:Date.now()-c},n),a}catch(r){throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:i,params:l,error:String(r),durationMs:Date.now()-c},n),r}}}})}var Qi=class{hooks=new Map;register(e){let t=this.hooks.get(e.hookName)??[];t.push(e),t.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,t)}async dispatch(e,t,n){let r=this.hooks.get(e)??[],i=[];for(let e of r){let r=await e.handler(t,n);i.push(r)}return i}};const Y={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function $i(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function ea(e){let t=$i(e?.warningThreshold,Y.warningThreshold),n=$i(e?.criticalThreshold,Y.criticalThreshold),r=$i(e?.globalCircuitBreakerThreshold,Y.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Y.enabled,historySize:$i(e?.historySize,Y.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Y.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Y.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Y.detectors.pingPong}}}function X(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ta(e,t){return`${e}:${Z(t)}`}function na(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(na).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${na(t[e])}`).join(`,`)}}`}function ra(e){try{return na(e)}catch{return e==null?`${e}`:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:e instanceof Error?`${e.name}:${e.message}`:Object.prototype.toString.call(e)}}function Z(e){let t=ra(e);return Te(`sha256`).update(t).digest(`hex`)}function ia(e,t){if(e===`command_status`)return!0;if(e!==`process`||!X(t))return!1;let n=t.action;return n===`poll`||n===`log`}function aa(e){return!X(e)||!Array.isArray(e.content)?``:e.content.filter(e=>X(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
68
- `).trim()}function oa(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:na(e)}function sa(e,t,n,r){if(r!==void 0)return`error:${Z(oa(r))}`;if(!X(n))return n===void 0?void 0:Z(n);let i=X(n.details)?n.details:{},a=aa(n);if(ia(e,t)&&e===`process`&&X(t)){let e=t.action;if(e===`poll`)return Z({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Z({action:e,status:i.status,totalLines:i.totalLines??null,totalChars:i.totalChars??null,truncated:i.truncated??null,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,text:a})}return Z({details:i,text:a})}function ca(e,t,n){let r=0,i;for(let a=e.length-1;a>=0;--a){let o=e[a];if(!(!o||o.toolName!==t||o.argsHash!==n)&&!(typeof o.resultHash!=`string`||!o.resultHash)){if(!i){i=o.resultHash,r=1;continue}if(o.resultHash!==i)break;r+=1}}return{count:r,latestResultHash:i}}function la(e,t){let n=e.at(-1);if(!n)return{count:0,noProgressEvidence:!1};let r,i;for(let t=e.length-2;t>=0;--t){let a=e[t];if(a&&a.argsHash!==n.argsHash){r=a.argsHash,i=a.toolName;break}}if(!r||!i)return{count:0,noProgressEvidence:!1};let a=0;for(let t=e.length-1;t>=0;--t){let i=e[t];if(!i)continue;let o=a%2==0?n.argsHash:r;if(i.argsHash!==o)break;a+=1}if(a<2||t!==r)return{count:0,noProgressEvidence:!1};let o=Math.max(0,e.length-a),s,c,l=!0;for(let t=o;t<e.length;t+=1){let i=e[t];if(i){if(!i.resultHash){l=!1;break}if(i.argsHash===n.argsHash){if(!s)s=i.resultHash;else if(s!==i.resultHash){l=!1;break}continue}if(i.argsHash===r){if(!c)c=i.resultHash;else if(c!==i.resultHash){l=!1;break}continue}l=!1;break}}return(!s||!c)&&(l=!1),{count:a+1,pairedToolName:n.toolName,pairedSignature:n.argsHash,noProgressEvidence:l}}function ua(e,t){return[e,t].toSorted().join(`|`)}function da(e,t,n,r){let i=ea(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=ta(t,n),s=ca(a,t,o),c=s.count,l=ia(t,n),u=la(a,o);if(c>=i.globalCircuitBreakerThreshold)return{stuck:!0,level:`critical`,detector:`global_circuit_breaker`,count:c,message:`CRITICAL: ${t} has repeated identical no-progress outcomes ${c} times. Session execution blocked by global circuit breaker to prevent runaway loops.`,warningKey:`global:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.criticalThreshold)return{stuck:!0,level:`critical`,detector:`known_poll_no_progress`,count:c,message:`CRITICAL: Called ${t} with identical arguments and no progress ${c} times. This appears to be a stuck polling loop. Session execution blocked to prevent resource waste.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`known_poll_no_progress`,count:c,message:`WARNING: You have called ${t} ${c} times with identical arguments and no progress. Stop polling and either (1) increase wait time between checks, or (2) report the task as failed if the process is stuck.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};let d=u.pairedSignature?`pingpong:${ua(o,u.pairedSignature)}`:`pingpong:${t}:${o}`;if(i.detectors.pingPong&&u.count>=i.criticalThreshold&&u.noProgressEvidence)return{stuck:!0,level:`critical`,detector:`ping_pong`,count:u.count,message:`CRITICAL: You are alternating between repeated tool-call patterns (${u.count} consecutive calls) with no progress. This appears to be a stuck ping-pong loop. Session execution blocked to prevent resource waste.`,pairedToolName:u.pairedToolName,warningKey:d};if(i.detectors.pingPong&&u.count>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`ping_pong`,count:u.count,message:`WARNING: You are alternating between repeated tool-call patterns (${u.count} consecutive calls). This looks like a ping-pong loop; stop retrying and report the task as failed.`,pairedToolName:u.pairedToolName,warningKey:d};let f=a.filter(e=>e.toolName===t&&e.argsHash===o).length;return!l&&i.detectors.genericRepeat&&f>=i.warningThreshold?{stuck:!0,level:`warning`,detector:`generic_repeat`,count:f,message:`WARNING: You have called ${t} ${f} times with identical arguments. If this is not making progress, stop retrying and report the task as failed.`,warningKey:`generic:${t}:${o}`}:{stuck:!1}}function fa(e,t,n,r,i){let a=ea(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:ta(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function pa(e,t){let n=ea(t.config),r=sa(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=ta(t.toolName,t.toolParams),a=!1;for(let n=e.toolCallHistory.length-1;n>=0;--n){let o=e.toolCallHistory[n];if(o&&!(t.toolCallId&&o.toolCallId!==t.toolCallId)&&!(o.toolName!==t.toolName||o.argsHash!==i)&&o.resultHash===void 0){o.resultHash=r,a=!0;break}}a||e.toolCallHistory.push({toolName:t.toolName,argsHash:i,toolCallId:t.toolCallId,resultHash:r,timestamp:Date.now()}),e.toolCallHistory.length>n.historySize&&e.toolCallHistory.splice(0,e.toolCallHistory.length-n.historySize)}function ma(e,t,n){e.toolLoopWarningBuckets||=new Map;let r=Math.floor(n/10);if(r<=(e.toolLoopWarningBuckets.get(t)??0))return!1;if(e.toolLoopWarningBuckets.set(t,r),e.toolLoopWarningBuckets.size>256){let t=e.toolLoopWarningBuckets.keys().next().value;t&&e.toolLoopWarningBuckets.delete(t)}return!0}function ha(e){return e&&e.trim()||`tool`}function ga(e,t,n){if(!e.execute)return e;let r=ha(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=da(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);ma(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}fa(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return pa(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw pa(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function _a(e,t,n){return e.map(e=>ga(e,t,n))}async function va(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,effectivePromptText:u,pluginTools:d},dependencies:{registry:f,spawnFn:p,createModel:m,abortSignal:h}}=e,g=t.channel===`CRON`,_=g?[]:await w(t.dataDir,n),v={model:t.llm.model,api:`openai-completions`},y=await ar({dataDir:t.dataDir,sessionId:n}),b=g?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await or({entries:_,modelInfo:v,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,signal:h,hooks:r,hookCtx:i,contextManager:y,dataDir:t.dataDir,sessionId:n});await ya({sessionId:n,historyResult:b,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let x=t.subagentContext?.depth??0,S=[...Ai(t.dataDir,{registry:f,parentSessionId:n,depth:x,channel:t.channel,llm:t.llm,inheritedRunParams:{plugins:t.plugins,memory:t.memory,messaging:t.messaging,docs:t.docs,historyLimit:t.historyLimit,onProgress:t.onProgress,messageId:t.messageId},loopDetection:t.loopDetection,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,onMemoryChanged:async()=>{}},contextManager:y,spawnFn:p}),...d],C=S.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),T={};for(let e of S){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||T[t]||(T[t]=n)}let E=t.messaging?.enabled??t.channel!==`CRON`,D=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],O=Xi({dataDir:t.dataDir,skills:l,contextFiles:s,toolNames:C,toolSummaries:T,promptMode:x>0?`minimal`:`full`,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:E,channels:D},docs:{localPath:t.docs?.localPath,webUrl:t.docs?.webUrl,sourceUrl:t.docs?.sourceUrl},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:Oe.hostname()},currentDate:new Date().toISOString().split(`T`)[0],priorConversationSummary:b.priorSummary}),k=await r.dispatch(`before_prompt_build`,{prompt:u},i);for(let e of k)e&&(e.systemPrompt&&(O=e.systemPrompt),e.prependContext&&(O=`${e.prependContext}\n\n${O}`));await r.dispatch(`after_prompt_build`,{prompt:u,systemPrompt:O},i);let A=_a(Zi(S,r,i),{sessionId:n,config:t.loopDetection},Ze),j=t.llm.model,M=await r.dispatch(`before_model_resolve`,{prompt:u},i);for(let e of M)e&&e.modelOverride&&(j=e.modelOverride);let N=m({...t.llm,model:j},n),ee=new De({initialState:{systemPrompt:O,model:N,tools:A,messages:[]},getApiKey:e=>t.llm.apiKey});return b.messages.length>0&&ee.replaceMessages(b.messages),{agent:ee,resolvedModelId:j,historyMessages:b.messages,historyResult:b,workspaceDir:a.workspaceDir}}async function ya(e){let{sessionId:t,historyResult:n,runContext:r,eventDispatcher:i,hookRegistry:a,hookContext:o}=e;for(let e of n.compactionEvents??[])e.type===`compaction`&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:e.reason,details:{layer:e.layer,strategy:e.strategy,estimatedTokensFreed:e.estimatedTokensFreed,affectedEntries:e.affectedEntries,snapshotVersion:e.snapshotVersion}});if(n.compactionEntry){let e=n.stats.originalCount-n.stats.keptCount;await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o),await r.appendTranscriptEntry(n.compactionEntry),(n.compactionEvents?.length??0)===0&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await a.dispatch(`after_compaction`,{messageCount:n.stats.originalCount,compactedCount:e},o)}}async function ba(e){let{agent:t,message:n,sessionId:r,modelId:i,historyMessages:a,eventDispatcher:o,skillUsageTracker:s,hooks:c,hookCtx:l,abortSignal:u}=e,d=``,f=``,p=``,m=0,h=0,g,_,v=0,y=[],b=t.subscribe(async e=>{if(e.type===`message_update`){let t=e.assistantMessageEvent;if(t.type===`text_delta`&&typeof t.delta==`string`){let n=Da(`partial`in t?t.partial:void 0)??Da(`message`in t?t.message:void 0)??Da(`message`in e?e.message:void 0),i=Oa(t.delta,n,f);i&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:i}),p+=i),n&&(f=n,p=n)}if(t.type===`done`){let e=t.message;d=Ea(e);let n=Oa(``,d,p||f);n&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:n}),p+=n),f=d,p=d,e.usage&&(m=e.usage.input,h=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(m=t.usage.input,h=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Ea(e);await c.dispatch(`assistant_message_end`,{sessionId:r,model:i,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:v>0?Math.max(0,Date.now()-v):void 0,usage:t.usage?{input:m,output:h,total:m+h}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(_=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=e.toolResults??[];y.push({message:t,toolResults:n.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:wa(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),r,e.toolCallId,e.toolName)}))});return}if(e.type===`tool_execution_start`){p=``,s.onToolExecutionStart({toolName:e.toolName,args:e.args}),await o.dispatchProgress(r,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args});return}if(e.type===`tool_execution_end`){await s.onToolExecutionEnd({toolName:e.toolName,isError:e.isError});let t=typeof e.result==`string`?e.result:JSON.stringify(e.result);await o.dispatchProgress(r,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,output:t,isError:e.isError})}});try{if(await c.dispatch(`llm_input`,{sessionId:r,model:i,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:a},l),u?.aborted)throw Error(`aborted`);if(v=Date.now(),await t.prompt(n),!g){let e=typeof t.state.error==`string`?t.state.error:void 0,n=_??e;n&&(g=ka(n),await o.dispatchProgress(r,{type:`error`,message:g}))}}catch(e){g=ka(e),await o.dispatchProgress(r,{type:`error`,message:g})}finally{b()}let x=y.length>0?y[y.length-1]?.message:void 0;return await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:d?[d]:[],lastAssistant:x,usage:{input:m,output:h,total:m+h}},l),{text:(y.length>0?Ea(y[y.length-1].message):``)||d,inputTokens:m,outputTokens:h,error:g,turnRecords:y}}async function xa(e,t){if(t.turnRecords.length>0){for(let n of t.turnRecords){let t=Sa(n.message);t&&await e(t);for(let t of n.toolResults)await e(Ca(t))}return}t.text&&await e({role:`assistant`,content:t.text,timestamp:new Date().toISOString()})}function Sa(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function Ca(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function wa(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:Ta(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Ta(e){let t=e.indexOf(`
68
+ `).trim()}function oa(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:na(e)}function sa(e,t,n,r){if(r!==void 0)return`error:${Z(oa(r))}`;if(!X(n))return n===void 0?void 0:Z(n);let i=X(n.details)?n.details:{},a=aa(n);if(ia(e,t)&&e===`process`&&X(t)){let e=t.action;if(e===`poll`)return Z({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Z({action:e,status:i.status,totalLines:i.totalLines??null,totalChars:i.totalChars??null,truncated:i.truncated??null,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,text:a})}return Z({details:i,text:a})}function ca(e,t,n){let r=0,i;for(let a=e.length-1;a>=0;--a){let o=e[a];if(!(!o||o.toolName!==t||o.argsHash!==n)&&!(typeof o.resultHash!=`string`||!o.resultHash)){if(!i){i=o.resultHash,r=1;continue}if(o.resultHash!==i)break;r+=1}}return{count:r,latestResultHash:i}}function la(e,t){let n=e.at(-1);if(!n)return{count:0,noProgressEvidence:!1};let r,i;for(let t=e.length-2;t>=0;--t){let a=e[t];if(a&&a.argsHash!==n.argsHash){r=a.argsHash,i=a.toolName;break}}if(!r||!i)return{count:0,noProgressEvidence:!1};let a=0;for(let t=e.length-1;t>=0;--t){let i=e[t];if(!i)continue;let o=a%2==0?n.argsHash:r;if(i.argsHash!==o)break;a+=1}if(a<2||t!==r)return{count:0,noProgressEvidence:!1};let o=Math.max(0,e.length-a),s,c,l=!0;for(let t=o;t<e.length;t+=1){let i=e[t];if(i){if(!i.resultHash){l=!1;break}if(i.argsHash===n.argsHash){if(!s)s=i.resultHash;else if(s!==i.resultHash){l=!1;break}continue}if(i.argsHash===r){if(!c)c=i.resultHash;else if(c!==i.resultHash){l=!1;break}continue}l=!1;break}}return(!s||!c)&&(l=!1),{count:a+1,pairedToolName:n.toolName,pairedSignature:n.argsHash,noProgressEvidence:l}}function ua(e,t){return[e,t].toSorted().join(`|`)}function da(e,t,n,r){let i=ea(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=ta(t,n),s=ca(a,t,o),c=s.count,l=ia(t,n),u=la(a,o);if(c>=i.globalCircuitBreakerThreshold)return{stuck:!0,level:`critical`,detector:`global_circuit_breaker`,count:c,message:`CRITICAL: ${t} has repeated identical no-progress outcomes ${c} times. Session execution blocked by global circuit breaker to prevent runaway loops.`,warningKey:`global:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.criticalThreshold)return{stuck:!0,level:`critical`,detector:`known_poll_no_progress`,count:c,message:`CRITICAL: Called ${t} with identical arguments and no progress ${c} times. This appears to be a stuck polling loop. Session execution blocked to prevent resource waste.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`known_poll_no_progress`,count:c,message:`WARNING: You have called ${t} ${c} times with identical arguments and no progress. Stop polling and either (1) increase wait time between checks, or (2) report the task as failed if the process is stuck.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};let d=u.pairedSignature?`pingpong:${ua(o,u.pairedSignature)}`:`pingpong:${t}:${o}`;if(i.detectors.pingPong&&u.count>=i.criticalThreshold&&u.noProgressEvidence)return{stuck:!0,level:`critical`,detector:`ping_pong`,count:u.count,message:`CRITICAL: You are alternating between repeated tool-call patterns (${u.count} consecutive calls) with no progress. This appears to be a stuck ping-pong loop. Session execution blocked to prevent resource waste.`,pairedToolName:u.pairedToolName,warningKey:d};if(i.detectors.pingPong&&u.count>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`ping_pong`,count:u.count,message:`WARNING: You are alternating between repeated tool-call patterns (${u.count} consecutive calls). This looks like a ping-pong loop; stop retrying and report the task as failed.`,pairedToolName:u.pairedToolName,warningKey:d};let f=a.filter(e=>e.toolName===t&&e.argsHash===o).length;return!l&&i.detectors.genericRepeat&&f>=i.warningThreshold?{stuck:!0,level:`warning`,detector:`generic_repeat`,count:f,message:`WARNING: You have called ${t} ${f} times with identical arguments. If this is not making progress, stop retrying and report the task as failed.`,warningKey:`generic:${t}:${o}`}:{stuck:!1}}function fa(e,t,n,r,i){let a=ea(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:ta(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function pa(e,t){let n=ea(t.config),r=sa(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=ta(t.toolName,t.toolParams),a=!1;for(let n=e.toolCallHistory.length-1;n>=0;--n){let o=e.toolCallHistory[n];if(o&&!(t.toolCallId&&o.toolCallId!==t.toolCallId)&&!(o.toolName!==t.toolName||o.argsHash!==i)&&o.resultHash===void 0){o.resultHash=r,a=!0;break}}a||e.toolCallHistory.push({toolName:t.toolName,argsHash:i,toolCallId:t.toolCallId,resultHash:r,timestamp:Date.now()}),e.toolCallHistory.length>n.historySize&&e.toolCallHistory.splice(0,e.toolCallHistory.length-n.historySize)}function ma(e,t,n){e.toolLoopWarningBuckets||=new Map;let r=Math.floor(n/10);if(r<=(e.toolLoopWarningBuckets.get(t)??0))return!1;if(e.toolLoopWarningBuckets.set(t,r),e.toolLoopWarningBuckets.size>256){let t=e.toolLoopWarningBuckets.keys().next().value;t&&e.toolLoopWarningBuckets.delete(t)}return!0}function ha(e){return e&&e.trim()||`tool`}function ga(e,t,n){if(!e.execute)return e;let r=ha(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=da(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);ma(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}fa(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return pa(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw pa(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function _a(e,t,n){return e.map(e=>ga(e,t,n))}async function va(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,effectivePromptText:u,pluginTools:d},dependencies:{registry:f,spawnFn:p,createModel:m,abortSignal:h}}=e,g=t.channel===`CRON`,_=g?[]:await w(t.dataDir,n),v={model:t.llm.model,api:`openai-completions`},y=await ar({dataDir:t.dataDir,sessionId:n}),b=g?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await or({entries:_,modelInfo:v,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,signal:h,hooks:r,hookCtx:i,contextManager:y,dataDir:t.dataDir,sessionId:n});await ya({sessionId:n,historyResult:b,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let x=t.subagentContext?.depth??0,S=[...Ai(t.dataDir,{registry:f,parentSessionId:n,depth:x,channel:t.channel,llm:t.llm,inheritedRunParams:{plugins:t.plugins,memory:t.memory,messaging:t.messaging,docs:t.docs,historyLimit:t.historyLimit,onProgress:t.onProgress,messageId:t.messageId},loopDetection:t.loopDetection,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,onMemoryChanged:async()=>{}},contextManager:y,spawnFn:p}),...d],C=S.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),T={};for(let e of S){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||T[t]||(T[t]=n)}let E=t.messaging?.enabled??t.channel!==`CRON`,D=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],O=Xi({dataDir:t.dataDir,skills:l,contextFiles:s,toolNames:C,toolSummaries:T,promptMode:x>0?`minimal`:`full`,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:E,channels:D},docs:{localPath:t.docs?.localPath,webUrl:t.docs?.webUrl,sourceUrl:t.docs?.sourceUrl},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:Oe.hostname()},currentDate:new Date().toISOString().split(`T`)[0],priorConversationSummary:b.priorSummary}),k=await r.dispatch(`before_prompt_build`,{prompt:u},i);for(let e of k)e&&(e.systemPrompt&&(O=e.systemPrompt),e.prependContext&&(O=`${e.prependContext}\n\n${O}`));await r.dispatch(`after_prompt_build`,{prompt:u,systemPrompt:O},i);let A=_a(Zi(S,r,i),{sessionId:n,config:t.loopDetection},Ze),j=t.llm.model,M=await r.dispatch(`before_model_resolve`,{prompt:u},i);for(let e of M)e&&e.modelOverride&&(j=e.modelOverride);let N=m({...t.llm,model:j},n),ee=new De({initialState:{systemPrompt:O,model:N,tools:A,messages:[]},getApiKey:e=>t.llm.apiKey});return b.messages.length>0&&ee.replaceMessages(b.messages),{agent:ee,resolvedModelId:j,historyMessages:b.messages,historyResult:b,workspaceDir:a.workspaceDir}}async function ya(e){let{sessionId:t,historyResult:n,runContext:r,eventDispatcher:i,hookRegistry:a,hookContext:o}=e;for(let e of n.compactionEvents??[])e.type===`compaction`&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:e.reason,details:{layer:e.layer,strategy:e.strategy,estimatedTokensFreed:e.estimatedTokensFreed,affectedEntries:e.affectedEntries,snapshotVersion:e.snapshotVersion}});if(n.compactionEntry){let e=n.stats.originalCount-n.stats.keptCount;await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o),await r.appendTranscriptEntry(n.compactionEntry),(n.compactionEvents?.length??0)===0&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await a.dispatch(`after_compaction`,{messageCount:n.stats.originalCount,compactedCount:e},o)}}async function ba(e){let{agent:t,message:n,sessionId:r,modelId:i,historyMessages:a,eventDispatcher:o,skillUsageTracker:s,hooks:c,hookCtx:l,abortSignal:u}=e,d=``,f=``,p=``,m=0,h=0,g,_,v=0,y=[],b=new Map,x=t.subscribe(async e=>{if(e.type===`message_update`){let t=e.assistantMessageEvent;if(t.type===`text_delta`&&typeof t.delta==`string`){let n=Da(`partial`in t?t.partial:void 0)??Da(`message`in t?t.message:void 0)??Da(`message`in e?e.message:void 0),i=Oa(t.delta,n,f);i&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:i}),p+=i),n&&(f=n,p=n)}if(t.type===`done`){let e=t.message;d=Ea(e);let n=Oa(``,d,p||f);n&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:n}),p+=n),f=d,p=d,e.usage&&(m=e.usage.input,h=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(m=t.usage.input,h=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Ea(e);await c.dispatch(`assistant_message_end`,{sessionId:r,model:i,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:v>0?Math.max(0,Date.now()-v):void 0,usage:t.usage?{input:m,output:h,total:m+h}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(_=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=e.toolResults??[];y.push({message:t,toolResults:n.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:wa(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),r,e.toolCallId,e.toolName)}))});return}if(e.type===`tool_execution_start`){p=``,b.set(e.toolCallId,e.args),s.onToolExecutionStart({toolName:e.toolName,args:e.args}),await o.dispatchProgress(r,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args});return}if(e.type===`tool_execution_end`){await s.onToolExecutionEnd({toolName:e.toolName,isError:e.isError});let t=typeof e.result==`string`?e.result:JSON.stringify(e.result),n=b.get(e.toolCallId);b.delete(e.toolCallId),await o.dispatchProgress(r,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:n,output:t,isError:e.isError})}});try{if(await c.dispatch(`llm_input`,{sessionId:r,model:i,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:a},l),u?.aborted)throw Error(`aborted`);if(v=Date.now(),await t.prompt(n),!g){let e=typeof t.state.error==`string`?t.state.error:void 0,n=_??e;n&&(g=ka(n),await o.dispatchProgress(r,{type:`error`,message:g}))}}catch(e){g=ka(e),await o.dispatchProgress(r,{type:`error`,message:g})}finally{x()}let S=y.length>0?y[y.length-1]?.message:void 0;return await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:d?[d]:[],lastAssistant:S,usage:{input:m,output:h,total:m+h}},l),{text:(y.length>0?Ea(y[y.length-1].message):``)||d,inputTokens:m,outputTokens:h,error:g,turnRecords:y}}async function xa(e,t){if(t.turnRecords.length>0){for(let n of t.turnRecords){let t=Sa(n.message);t&&await e(t);for(let t of n.toolResults)await e(Ca(t))}return}t.text&&await e({role:`assistant`,content:t.text,timestamp:new Date().toISOString()})}function Sa(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function Ca(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function wa(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:Ta(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Ta(e){let t=e.indexOf(`
69
69
  Preview:
70
70
  `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function Ea(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Da(e){if(!e||typeof e!=`object`)return null;let t=e;return Array.isArray(t.content)?t.content.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&`text`in e).map(e=>e.text).join(``):null}function Oa(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function ka(e){let t=Aa(e);return t?t.code===`http_error`&&t.statusCode?t.providerMessage?`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}: ${t.providerMessage}`:`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}`:t.code===`timeout`?`LLM request timed out`:t.code===`network_error`?t.message:t.code===`aborted`?`LLM request was aborted`:t.message:e instanceof Error?e.message:String(e)}function Aa(e){if(e instanceof B)return e;if(!(e instanceof Error))return null;let t=e;return e.name!==`LlmRequestError`&&!t.code?null:{message:e.message,code:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage}}async function ja(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,skillUsageTracker:o,hookRegistry:s,hookContext:c,abortSignal:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!l?.aborted&&n.needsAnnounce(r)&&d<10;){d++,await n.waitForAll(r);let e=n.consumeCompleted(r);if(e.length===0)break;for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=Ma(e);await u({role:`user`,content:g,timestamp:new Date().toISOString()});let _=await ba({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,skillUsageTracker:o,hooks:s,hookCtx:c,abortSignal:l});f=_.text,p+=_.inputTokens,m+=_.outputTokens,_.error&&!h&&(h=_.error),await xa(u,_)}return{text:f,inputTokens:p,outputTokens:m,error:h}}function Ma(e){if(e.length===1){let t=e[0];return Si({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Si({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
71
71
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/agents",
3
- "version": "0.0.19",
3
+ "version": "0.0.21",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -30,7 +30,7 @@
30
30
  "openai": "6.10.0",
31
31
  "sqlite-vec": "^0.1.6",
32
32
  "zod": "^4.3.6",
33
- "@gencode/shared": "0.0.6"
33
+ "@gencode/shared": "0.0.7"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@sinclair/typebox": "^0.34.48",