@gencode/agents 0.0.14 → 0.0.15
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/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -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??[])await i.dispatchProgress(t,e);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.dispatchProgress(t,{type:`compaction`,reason:`Summarised ${e} older entries`}),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=``,h=0,g=0,_,v,y=0,b=[],x=async()=>{d&&=(f=d,await o.dispatchProgress(r,{type:`text`,text:d}),``)},S=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),r=Oa(t.delta,n,m);d+=r,m=n??m+r}if(t.type===`done`){let e=t.message;if(p=Ea(e),!d){let e=Oa(``,p,m);e&&(d+=e,m=p)}e.usage&&(h=e.usage.input,g=e.usage.output),await x()}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(h=t.usage.input,g=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:y>0?Math.max(0,Date.now()-y):void 0,usage:t.usage?{input:h,output:g,total:h+g}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(v=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=e.toolResults??[];b.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`){await x(),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(y=Date.now(),await t.prompt(n),!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=ka(n),await o.dispatchProgress(r,{type:`error`,message:_}))}}catch(e){_=ka(e),await o.dispatchProgress(r,{type:`error`,message:_})}finally{S()}let C=b.length>0?b[b.length-1]?.message:void 0;return await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:p?[p]:f?[f]:[],lastAssistant:C,usage:{input:h,output:g,total:h+g}},l),{text:(b.length>0?Ea(b[b.length-1].message):``)||p||f,inputTokens:h,outputTokens:g,error:_,turnRecords:b}}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??[])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=``,h=0,g=0,_,v,y=0,b=[],x=async()=>{d&&=(f=d,await o.dispatchProgress(r,{type:`text`,text:d}),``)},S=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),r=Oa(t.delta,n,m);d+=r,m=n??m+r}if(t.type===`done`){let e=t.message;if(p=Ea(e),!d){let e=Oa(``,p,m);e&&(d+=e,m=p)}e.usage&&(h=e.usage.input,g=e.usage.output),await x()}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(h=t.usage.input,g=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:y>0?Math.max(0,Date.now()-y):void 0,usage:t.usage?{input:h,output:g,total:h+g}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(v=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=e.toolResults??[];b.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`){await x(),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(y=Date.now(),await t.prompt(n),!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=ka(n),await o.dispatchProgress(r,{type:`error`,message:_}))}}catch(e){_=ka(e),await o.dispatchProgress(r,{type:`error`,message:_})}finally{S()}let C=b.length>0?b[b.length-1]?.message:void 0;return await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:p?[p]:f?[f]:[],lastAssistant:C,usage:{input:h,output:g,total:h+g}},l),{text:(b.length>0?Ea(b[b.length-1].message):``)||p||f,inputTokens:h,outputTokens:g,error:_,turnRecords:b}}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
|
|