agentix-cli 0.20.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-57MG4LBM.js → agent-Y4U4R3ZZ.js} +2 -2
- package/dist/{board-dashboard-HXDOYGIG.js → board-dashboard-2CPBWFOB.js} +339 -97
- package/dist/board-dashboard-2CPBWFOB.js.map +1 -0
- package/dist/chunk-2HXSJYAJ.js +15 -0
- package/dist/chunk-2HXSJYAJ.js.map +1 -0
- package/dist/{chunk-QW2OYR3N.js → chunk-ABVZHJUO.js} +2 -2
- package/dist/chunk-BHSPAP4U.js +44 -0
- package/dist/chunk-BHSPAP4U.js.map +1 -0
- package/dist/chunk-CO4YCIIA.js +13 -0
- package/dist/chunk-CO4YCIIA.js.map +1 -0
- package/dist/{chunk-4MREHZP5.js → chunk-GOLZ6NEL.js} +2 -2
- package/dist/chunk-GOLZ6NEL.js.map +1 -0
- package/dist/chunk-GSX4NK2N.js +2 -0
- package/dist/chunk-GSX4NK2N.js.map +1 -0
- package/dist/chunk-GV7S5BAX.js +2 -0
- package/dist/chunk-GV7S5BAX.js.map +1 -0
- package/dist/{chunk-WPPUOTY6.js → chunk-KX626FN4.js} +2 -2
- package/dist/chunk-OPKQNLGX.js +450 -0
- package/dist/chunk-OPKQNLGX.js.map +1 -0
- package/dist/chunk-OZOQKPJV.js +102 -0
- package/dist/chunk-OZOQKPJV.js.map +1 -0
- package/dist/{chunk-DLVOHCTA.js → chunk-P3TJHGO5.js} +2 -2
- package/dist/chunk-SZDACK6O.js +2 -0
- package/dist/chunk-SZDACK6O.js.map +1 -0
- package/dist/{chunk-TC3BSUP7.js → chunk-VYLZ7UYM.js} +2 -2
- package/dist/{chunk-WFHIIVLL.js → chunk-WHP4I44J.js} +75 -51
- package/dist/chunk-WHP4I44J.js.map +1 -0
- package/dist/chunk-X5D5AV5N.js +833 -0
- package/dist/chunk-X5D5AV5N.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/{config-QXWKEQON.js → config-BLOKGMER.js} +2 -2
- package/dist/config-mutator-RG7QY2EL.js +2 -0
- package/dist/doctor-ZTECTUHX.js +2 -0
- package/dist/index.d.ts +140 -3
- package/dist/index.js +1 -1
- package/dist/program-GZOJIWTB.js +2 -0
- package/dist/registry-QZIUSQ5J.js +2 -0
- package/dist/runner-BFYDWPUO.js +2 -0
- package/dist/scheduler-B2BQPV4M.js +2 -0
- package/dist/store-I3HEWVLQ.js +2 -0
- package/dist/store-I3HEWVLQ.js.map +1 -0
- package/dist/types-Y6ZCZ52Z.js +2 -0
- package/dist/types-Y6ZCZ52Z.js.map +1 -0
- package/dist/web/workflow-editor.global.js +12 -10
- package/dist/web/workflow-editor.global.js.map +1 -1
- package/dist/workspace-setup-DQCZX2NE.js +2 -0
- package/dist/workspace-setup-DQCZX2NE.js.map +1 -0
- package/package.json +1 -1
- package/dist/board-dashboard-HXDOYGIG.js.map +0 -1
- package/dist/chunk-23AUU4S2.js +0 -102
- package/dist/chunk-23AUU4S2.js.map +0 -1
- package/dist/chunk-4MREHZP5.js.map +0 -1
- package/dist/chunk-6B74TO2J.js +0 -743
- package/dist/chunk-6B74TO2J.js.map +0 -1
- package/dist/chunk-7GVXCOLO.js +0 -440
- package/dist/chunk-7GVXCOLO.js.map +0 -1
- package/dist/chunk-E4ZZILAK.js +0 -15
- package/dist/chunk-E4ZZILAK.js.map +0 -1
- package/dist/chunk-MBOLXKA2.js +0 -6
- package/dist/chunk-MBOLXKA2.js.map +0 -1
- package/dist/chunk-WFHIIVLL.js.map +0 -1
- package/dist/chunk-ZE2YFX4K.js +0 -45
- package/dist/chunk-ZE2YFX4K.js.map +0 -1
- package/dist/config-mutator-53XGR2NT.js +0 -2
- package/dist/doctor-SEOUFHSL.js +0 -2
- package/dist/program-WWCXMRU2.js +0 -2
- package/dist/registry-HM4ELSXS.js +0 -2
- package/dist/scheduler-XVFIK4XH.js +0 -2
- package/dist/workspace-setup-FPGN5VNY.js +0 -2
- /package/dist/{agent-57MG4LBM.js.map → agent-Y4U4R3ZZ.js.map} +0 -0
- /package/dist/{chunk-QW2OYR3N.js.map → chunk-ABVZHJUO.js.map} +0 -0
- /package/dist/{chunk-WPPUOTY6.js.map → chunk-KX626FN4.js.map} +0 -0
- /package/dist/{chunk-DLVOHCTA.js.map → chunk-P3TJHGO5.js.map} +0 -0
- /package/dist/{chunk-TC3BSUP7.js.map → chunk-VYLZ7UYM.js.map} +0 -0
- /package/dist/{config-QXWKEQON.js.map → config-BLOKGMER.js.map} +0 -0
- /package/dist/{config-mutator-53XGR2NT.js.map → config-mutator-RG7QY2EL.js.map} +0 -0
- /package/dist/{doctor-SEOUFHSL.js.map → doctor-ZTECTUHX.js.map} +0 -0
- /package/dist/{program-WWCXMRU2.js.map → program-GZOJIWTB.js.map} +0 -0
- /package/dist/{registry-HM4ELSXS.js.map → registry-QZIUSQ5J.js.map} +0 -0
- /package/dist/{scheduler-XVFIK4XH.js.map → runner-BFYDWPUO.js.map} +0 -0
- /package/dist/{workspace-setup-FPGN5VNY.js.map → scheduler-B2BQPV4M.js.map} +0 -0
package/dist/chunk-23AUU4S2.js
DELETED
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
import{a as Ke}from"./chunk-5F3J55LG.js";import{a as qe,b as Ge,d as Je}from"./chunk-WJXU5F4Z.js";import{c as ze}from"./chunk-4MREHZP5.js";import{b as Ue,c as We,f as Be}from"./chunk-7P5QRX5W.js";import{a as ke,b as Qe}from"./chunk-SR3X25TN.js";import{a as we,b as Xe}from"./chunk-53NRX2NA.js";import{a as xe}from"./chunk-A6BKSZQA.js";import{e as L}from"./chunk-DSYKYZMT.js";import{a as Le}from"./chunk-IKBHHTIT.js";import{c as oe,d as ie}from"./chunk-QOYAX2FT.js";import{execa as Ft}from"execa";import{execFile as Lt}from"child_process";import{StringDecoder as Ut}from"string_decoder";function B(o){let e=(o||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let s=n?.error||n,r=typeof s?.type=="string"?s.type:void 0,i=typeof s?.message=="string"?s.message:void 0,c=e.match(/API Error:\s*(\d{3})/i),a=c?parseInt(c[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:r==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:r==="permission_error"||a===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:r==="rate_limit_error"||a===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:r==="overloaded_error"||a===529||a===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:r==="invalid_request_error"||a===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:a&&a>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${a}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function K(o){return o.fix?`${o.message} \u2014 ${o.fix}`:o.message}function Se(o,e,t){let n=[];if(e.context&&!t){let s=e.context,r=["","[Environment]"],i=s.channel==="gitlab"||s.channel?.startsWith("webhook:"),c=s.channel==="telegram";if(s.channel&&r.push(`Channel: ${s.channel}`),s.group&&r.push(`Group: ${s.group}`),s.sender&&r.push(`Message from: ${s.sender}`),s.myHandle&&r.push(`Your handle on this channel: ${s.myHandle}`),i&&(r.push(""),r.push("[IMPORTANT: You are responding to a GitLab comment/event]"),r.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),r.push("- Lead with the result or action, not a narration of what you plan to do"),r.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),r.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),r.push("- Do NOT try to delegate to other agents \u2014 reply directly"),r.push("- Reference issues with #IID and MRs with !IID")),c&&s.peers?.length){r.push(""),r.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let a of s.peers){let u=a.handle?` (mention: ${a.handle})`:"",h=a.role?` \u2014 ${a.role}`:"";r.push(`\u2022 ${a.name}${u}${h}`)}r.push(""),r.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(r.join(`
|
|
2
|
-
`))}return e.context?.replyToText&&(n.push(""),n.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(n.push(""),n.push(`[Attached file: ${e.context.mediaPath}]`),n.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?n.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?n.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?n.push("A video file is attached. Describe what you can determine about it."):n.push("Please read this file and respond based on its content.")),t&&(n.push(""),n.push(t)),n.push(""),n.push(e.message),n.join(`
|
|
3
|
-
`)}function Ye(o,e,t,n,s,r){let i=["-p",e,"--output-format",t?"stream-json":"json"];t&&i.push("--verbose"),n&&i.push("--resume",n);let c=s||o.model;return c&&i.push("--model",c),o.permissionMode==="bypassPermissions"&&i.push("--dangerously-skip-permissions"),r&&r.trim().length>0&&i.push("--append-system-prompt",r),i}function Wt(o){try{let e=JSON.parse(o);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function Bt(o){try{let e=JSON.parse(o),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,n=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:n}}catch{return{text:o}}}async function Kt(o,e,t,n){let s=Date.now(),r=Se(o,e,t),i=Ye(o,r,!1,n,e.model,e.systemPromptAppend);try{let c=Math.max(6e4,(o.maxExecutionMinutes??20)*6e4),{stdout:a,stderr:u,exitCode:h}=await new Promise((p,k)=>{let f=xe(o.workspace);Lt("claude",i,{cwd:o.workspace,timeout:c,maxBuffer:10*1024*1024,env:{...f,HOME:f.HOME||"/home/"+(f.USER||"user")}},(I,x,R)=>{p({stdout:x||"",stderr:R||"",exitCode:I?I.code??1:0})}).stdin?.end()});if(!a&&h!==0){let p;return h===143?p=`Claude Code timed out after ${Math.round(c/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${o.name||"this agent"}" if tasks need longer.`:p=u?.trim()||`Claude Code exited with code ${h}`,{content:"",error:K(B(p)),duration:Date.now()-s}}let d=Wt(a);if(d)return{content:"",error:K(B(d)),duration:Date.now()-s};let g=Bt(a);return{content:g.text,duration:Date.now()-s,claudeSessionId:g.sessionId,usage:g.usage,billedModel:g.billedModel}}catch(c){return console.error(`[runtime] execFile threw: ${c.message}`),{content:"",error:c.message||"Claude Code failed",duration:Date.now()-s}}}async function qt(o,e,t,n,s,r){let i=Date.now(),c=Se(o,e,n),a=Ye(o,c,!0,s,e.model,e.systemPromptAppend),u="",h,d,g,p;try{let k=Math.max(6e4,(o.maxExecutionMinutes??20)*6e4),f=Ft("claude",a,{cwd:o.workspace,timeout:k,reject:!1,env:xe(o.workspace),buffer:!1,stdin:"ignore"}),w="",I=new Ut("utf8");f.stdout&&f.stdout.on("data",$=>{w+=I.write($);let T=w.split(`
|
|
4
|
-
`);w=T.pop()||"";for(let v of T)if(v.trim())try{let y=JSON.parse(v);if(r)try{r(y)}catch{}if(y.type==="assistant"&&y.message?.content){for(let C of y.message.content)if(C.type==="text"&&C.text){let O=C.text.slice(u.length);O&&(u=C.text,t(O,u))}}if(y.type==="content_block_delta"&&y.delta?.text&&(u+=y.delta.text,t(y.delta.text,u)),y.type==="result"&&y.result){if(y.is_error&&typeof y.result=="string")p=y.result;else{let C=(typeof y.result=="string",y.result);if(typeof C=="string"&&C.length>u.length){let O=C.slice(u.length);u=C,O&&t(O,u)}}y.usage&&(d={inputTokens:y.usage.input_tokens||0,outputTokens:y.usage.output_tokens||0,cacheReadTokens:y.usage.cache_read_input_tokens||0,cacheCreateTokens:y.usage.cache_creation_input_tokens||0}),typeof y.model=="string"&&(h=y.model),typeof y.session_id=="string"&&(g=y.session_id)}y.type==="system"&&y.subtype==="init"&&typeof y.model=="string"&&(h=y.model)}catch{v.trim()&&!v.startsWith("{")&&(u+=v+`
|
|
5
|
-
`,t(v+`
|
|
6
|
-
`,u))}});let x=await f,R=I.end();if(R&&(w+=R),!u&&x.stdout&&(u=typeof x.stdout=="string"?x.stdout:""),x.exitCode!==0&&!u){let $=typeof x.stderr=="string"?x.stderr:"",T=x,v;return T.timedOut?v=`Claude Code timed out after ${Math.round(k/6e4)}m. Bump agent.maxExecutionMinutes for "${o.name||"this agent"}" if tasks need longer.`:T.signal?v=$.trim()||`Claude Code killed by signal ${T.signal}`:v=$.trim()||`Claude Code exited with code ${T.exitCode??"unknown"}`,{content:"",error:K(B(v)),duration:Date.now()-i}}return p?{content:"",error:K(B(p)),duration:Date.now()-i,usage:d,billedModel:h,claudeSessionId:g}:{content:u,duration:Date.now()-i,usage:d,billedModel:h,claudeSessionId:g}}catch(k){return{content:u||"",error:K(B(k.message)),duration:Date.now()-i,usage:d,billedModel:h,claudeSessionId:g}}}async function Gt(o,e,t,n){let s=Date.now();try{let r=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=r,c=Se(o,e,n),a="",u=i({prompt:c,options:{model:e.model||o.model,cwd:o.workspace,permissionMode:"bypassPermissions"}});for await(let h of u)h.type==="result"&&h.subtype==="success"&&(a=h.result||"");return{content:a,duration:Date.now()-s}}catch(r){return{content:"",error:`SDK error: ${r.message}`,duration:Date.now()-s}}}async function Jt(o,e,t,n){let s=Date.now();try{let{generate:r}=await import("./agent-57MG4LBM.js"),i=o.provider||"claude-code",c=n?`${n}
|
|
7
|
-
|
|
8
|
-
${e.message}`:e.message,a=await r({task:c,cwd:o.workspace,provider:i,model:e.model||o.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1});return{content:a.content||"Done.",tokensUsed:a.tokensUsed,duration:Date.now()-s}}catch(r){return{content:"",error:`Orchestrator error: ${r.message}`,duration:Date.now()-s}}}async function Ze(o,e,t,n,s,r,i){switch(o.tier){case"claude-code":return n?qt(o,e,n,s,r,i):Kt(o,e,s,r);case"sdk":{let c=o.provider||"claude",a=t[c]?.apiKey;return a?Gt(o,e,a,s):{content:"",error:`No API key for provider "${c}". Configure providers.${c}.apiKey`}}case"orchestrator":{let c=o.provider||"claude-code",a=t[c]?.apiKey;return Jt(o,e,a,s)}default:return{content:"",error:`Unknown tier: ${o.tier}`}}}import{readFileSync as ae,writeFileSync as Qt,mkdirSync as zt,existsSync as Ve,readdirSync as Ce}from"fs";import{resolve as Y}from"path";var et=12e3,ce=30,Xt=45,Yt=15,Zt=18e4,Vt="[Compacted conversation summary",en=[/\bearlier\b/i,/\bbefore\b/i,/\bjust said\b/i,/\btold (?:me|you|us|him|her|them)\b/i,/\bmention(?:ed|ing)?\b/i,/\bask(?:ed)? (?:me|you|him|her|them|about)\b/i,/\bping(?:ed)?\b/i,/\bdm\b/i,/\bdirect message\b/i,/\bother (?:chat|group|conversation|thread)\b/i,/\bthat (?:chat|group|conversation|thread)\b/i,/\bsame (?:issue|thread|conversation)\b/i,/\bcontinuing\b/i,/@\w{2,}_?(?:bot|agent)\b/i,/قلت/,/قال(?:لك|لي|له|لها|لنا)?/,/قبل/,/الحين/,/الثاني/,/المجموعة/];function tn(o){return o?en.some(e=>e.test(o)):!1}var nn=[{re:/\byesterday\b/i,days:2},{re:/\bأمس\b/,days:2},{re:/\bcouple (?:of )?days\b/i,days:4},{re:/\bfew days\b/i,days:4},{re:/\blast week\b/i,days:8},{re:/\bالأسبوع الماضي\b/,days:8},{re:/\bweek ago\b/i,days:8},{re:/\bremember\b/i,days:3},{re:/\bpreviously\b/i,days:3},{re:/\bwe (?:discussed|talked|agreed|decided)\b/i,days:3},{re:/\bas (?:i|we) (?:said|told|mentioned)\b/i,days:3},{re:/\bcontinue from\b/i,days:3},{re:/\bتذكر\b/,days:3}];function nt(o){if(!o)return null;let e=0;for(let t of nn)t.re.test(o)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function tt(o,e,t,n){if(o.length===0)return!1;let s=o[o.length-1];return s.role===e&&(s.name??"")===t&&s.content===n}function sn(o){let e=o.slice(11,16),t=e.slice(0,2),n=parseInt(e.slice(3,5),10);if(Number.isNaN(n))return e;let s=Math.floor(n/15)*15;return`${t}:${s.toString().padStart(2,"0")}`}var ue=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Y(e,".agentx/sessions"),Ve(this.sessionsDir)||zt(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Xt),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??Yt),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Zt)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n){if(!this.adapterResolver)return;let s=this.sessionKey(e,t,n),r=this.seedingPromises.get(s);if(r)return r;let i=this.getSession(e,t,n);if(i.messages.length>0)return;let c=this.adapterResolver(t);if(!c?.seedHistory)return;let a=(async()=>{try{let u=await c.seedHistory(n,{maxMessages:ce,maxChars:et});u.length>0&&this.appendSeededMessages(i,u)}catch{}})();this.seedingPromises.set(s,a);try{await a}finally{this.seedingPromises.delete(s)}}appendSeededMessages(e,t){if(t.length===0)return;let n=new Set;for(let r of e.messages)r.externalId&&n.add(r.externalId);let s=0;for(let r of t)r.externalId&&n.has(r.externalId)||(e.messages.push({role:r.role,name:r.name,content:r.content,timestamp:r.timestamp,seeded:!0,externalId:r.externalId}),s++);s!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,n){let s=new Date().toISOString().slice(0,10);return`${e}:${t}:${n}:${s}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Y(this.sessionsDir,`${t}.json`)}getSession(e,t,n){let s=this.sessionKey(e,t,n);if(this.cache.has(s))return this.cache.get(s);let r=this.sessionFile(s);if(Ve(r))try{let a=JSON.parse(ae(r,"utf-8"));return this.cache.set(s,a),a}catch{}let i=new Date().toISOString().slice(0,10),c={id:s,agentId:e,channel:t,chatId:n,day:i,messages:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return this.cache.set(s,c),this.save(c),c}addUserMessage(e,t,n,s,r){let i=this.getSession(e,t,n);tt(i.messages,"user",s,r)||(i.messages.push({role:"user",name:s,content:r,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}addAgentMessage(e,t,n,s){let r=this.getSession(e,t,n);tt(r.messages,"agent",e,s)||(r.messages.push({role:"agent",name:e,content:s,timestamp:new Date().toISOString()}),this.trim(r),r.updatedAt=new Date().toISOString(),this.save(r))}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,s){let r=this.getSession(e,t,n);r.claudeSessionId=s,r.updatedAt=new Date().toISOString(),this.save(r)}buildHistoryContext(e,t,n){let s=this.getSession(e,t,n);if(s.messages.length===0)return"";let r=[`[Conversation history for today (${s.day})]`],i="";for(let c of s.messages){let a=sn(c.timestamp);a!==i&&(r.push(`\u2014 ${a} \u2014`),i=a);let u=c.name||(c.role==="user"?"User":"Agent");r.push(`${u}: ${c.content}`)}return r.push("[End of history \u2014 respond to the latest message above]"),r.push(""),r.join(`
|
|
9
|
-
`)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),n=new Date;n.setUTCHours(0,0,0,0);let s=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():n.toISOString(),r=e.after??s,i=e.before??new Date(Date.now()+1e3).toISOString(),c=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),a;try{a=Ce(this.sessionsDir).filter($=>$.startsWith(`${c}:`)&&$.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let u=r.slice(0,10),h=i.slice(0,10),d=/:(\d{4}-\d{2}-\d{2})\.json$/,g=a.filter($=>{let T=$.match(d);if(!T)return!1;let v=T[1];return v>=u&&v<=h}),p=[],k=0,f=e.query?.toLowerCase(),w=e.participants?.length?new Set(e.participants):void 0;for(let $ of g){let T;try{T=JSON.parse(ae(Y(this.sessionsDir,$),"utf-8"))}catch{continue}if(T.agentId===e.agentId&&!(e.channel&&T.channel!==e.channel)&&!(e.chatId&&T.chatId!==e.chatId))for(let v of T.messages)k++,!(!v.timestamp||v.timestamp<r||v.timestamp>=i)&&(w&&v.role==="user"&&!w.has(v.name??"")||f&&!v.content.toLowerCase().includes(f)||p.push({ts:v.timestamp,role:v.role,senderName:v.name??"",content:v.content,channel:T.channel,chatId:T.chatId,day:T.day,sessionFile:$}))}p.sort(($,T)=>T.ts.localeCompare($.ts));let I=p.slice(0,t),x=I.length>0?I[I.length-1].ts:null,R=p.length>t;return{turns:I,oldestTs:x,hasMore:R,totalScanned:k}}recentByChatId(e){let t=Math.min(Math.max(e.limit??ce,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),s=n.slice(0,10),r;try{r=Ce(this.sessionsDir).filter(d=>d.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`,c=r.filter(d=>{if(!d.includes(i))return!1;let g=d.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=s:!1}),a=[];for(let d of c){let g;try{g=JSON.parse(ae(Y(this.sessionsDir,d),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let p of g.messages)!p.timestamp||p.timestamp<n||a.push({ts:p.timestamp,role:p.role,senderName:p.name??"",content:p.content,agentId:g.agentId,sessionFile:d})}let u=new Set,h=[];for(let d of a){let g=`${d.ts}|${d.role}|${d.senderName}|${d.content}`;u.has(g)||(u.add(g),h.push(d))}return h.sort((d,g)=>d.ts.localeCompare(g.ts)),h.slice(-t)}isSessionStale(e,t,n){let s=this.getSession(e,t,n);return s.claudeSessionId?Date.now()-new Date(s.updatedAt).getTime()>this.staleMinutes*60*1e3:!1}getCrossSessionSummary(e,t,n,s){if(s!==void 0&&s!==""&&!tn(s))return"";let r=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let c=Ce(this.sessionsDir).filter(u=>u.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&u.includes(r)&&u.endsWith(".json")),a=[];for(let u of c)try{let h=JSON.parse(ae(Y(this.sessionsDir,u),"utf-8"));if(h.id===i||h.messages.length===0)continue;let d=h.messages.slice(-4),p=!h.chatId.startsWith("-")&&/^\d+$/.test(h.chatId)?"DM":h.chatId,k=d.map(f=>` [${f.timestamp.slice(11,16)}] ${f.name||f.role}: ${f.content.slice(0,200)}`);a.push(`From ${p} (${h.channel}):
|
|
10
|
-
${k.join(`
|
|
11
|
-
`)}`)}catch{}return a.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...a,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
|
|
12
|
-
`)}catch{return""}}async compactIfNeeded(e,t,n,s){let r=this.getSession(e,t,n),{needsCompaction:i,compactSession:c,applyCompaction:a}=await import("./compaction-BTUJJ3LJ.js");if(!i(r.messages))return{compacted:!1};let u=await c(r.messages,e,s);return u.compactedCount===0?{compacted:!1}:(r.messages=a(r.messages,u),r.updatedAt=new Date().toISOString(),this.save(r),{compacted:!0,qualityScore:u.qualityScore,lostEntities:u.lostEntities,drift:u.drift})}hasCompaction(e,t,n){let s=this.getSession(e,t,n);return s.messages.length>0&&s.messages[0].content.startsWith(Vt)}clearClaudeSessionId(e,t,n){let s=this.getSession(e,t,n);delete s.claudeSessionId,delete s.turnCount,delete s.lastTurnInputTokens,s.updatedAt=new Date().toISOString(),this.save(s)}shouldRotateByTurns(e,t,n){let s=this.getSession(e,t,n);return s.claudeSessionId?(s.turnCount??0)>=this.maxTurnsPerSession:!1}shouldRotateByTierTwo(e,t,n){let s=this.getSession(e,t,n);return s.claudeSessionId?(s.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens:!1}recordTurnUsage(e,t,n,s){let r=this.getSession(e,t,n);r.turnCount=(r.turnCount??0)+1,r.lastTurnInputTokens=(s.inputTokens||0)+(s.cacheReadTokens||0)+(s.cacheCreateTokens||0),r.updatedAt=new Date().toISOString(),this.save(r)}getTurnCount(e,t,n){return this.getSession(e,t,n).turnCount??0}getLastTurnInputTokens(e,t,n){return this.getSession(e,t,n).lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>ce&&(e.messages=e.messages.slice(-ce));let n=e.messages.reduce((r,i)=>r+i.content.length,0);for(;n>et&&e.messages.length>2;){let r=e.messages.shift();n-=r.content.length}let s=t-e.messages.length;s>0&&L.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${s} message(s): ${t} -> ${e.messages.length} (${n}c)`)}save(e){try{let t=this.sessionFile(e.id);Qt(t,JSON.stringify(e,null,2))}catch{}}};var de=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],s=t-36e5,r=n.filter(a=>a>s),i=t-6e4,c=r.filter(a=>a>i);if(c.length>=this.maxPerMinute){let a=c[0],u=Math.max(50,a+6e4-t);return{allowed:!1,reason:`Rate limit: ${c.length}/${this.maxPerMinute} per minute`,waitMs:u}}if(r.length>=this.maxPerHour){let a=r[0],u=Math.max(1e3,a+36e5-t);return{allowed:!1,reason:`Rate limit: ${r.length}/${this.maxPerHour} per hour`,waitMs:u}}return r.push(t),this.windows.set(e,r),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,s=Date.now()+n,r=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=s)return{ok:!1,reason:`${i.reason} (waited ${Math.round(n/1e3)}s, giving up)`};r&&(r=!1,t.onWait?.(i.reason,i.waitMs));let c=s-Date.now(),a=Math.min(i.waitMs??1e3,c,5e3);await new Promise(u=>setTimeout(u,a))}}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(s=>s>t-6e4).length,lastHour:n.filter(s=>s>t-36e5).length}}};import{readFileSync as Z,writeFileSync as st,appendFileSync as rn,existsSync as q,mkdirSync as on}from"fs";import{resolve as G}from"path";var ot={"claude-opus-4-6":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus":{input:15,output:75,cacheRead:1.5,cacheCreate:18.75},"claude-sonnet":{input:3,output:15,cacheRead:.3,cacheCreate:3.75},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheCreate:1.25}},it=2e5,an=1.5;function cn(o){let e=o.toLowerCase();return e.includes("opus")?e.includes("4-6")||e.includes("4.6")||e.includes("opus-4-6")?"claude-opus-4-6":e.includes("4-5")||e.includes("4.5")||e.includes("opus-4-5")?"claude-opus-4-5":"claude-opus":e.includes("haiku")?"claude-haiku":"claude-sonnet"}function at(o){return o.inputTokens+o.cacheReadTokens+o.cacheCreateTokens>it?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:o.inputTokens,tier2OutputTokens:o.outputTokens,tier2CacheReadTokens:o.cacheReadTokens,tier2CacheCreateTokens:o.cacheCreateTokens}:{inputTokens:o.inputTokens,outputTokens:o.outputTokens,cacheReadTokens:o.cacheReadTokens,cacheCreateTokens:o.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var rt=500,un=".agentx/pricing/custom.json",J=class{dir;cache=null;pricing;constructor(e=G(process.cwd(),".agentx/usage")){this.dir=e,on(this.dir,{recursive:!0}),this.pricing=dn()}getPricing(){return this.pricing}static calculateCost(e,t,n=ot){let s=cn(t||e.model||"claude-sonnet"),r=n[s]||n["claude-sonnet"],i=e.tier2InputTokens||0,c=e.tier2OutputTokens||0,a=e.tier2CacheReadTokens||0,u=e.tier2CacheCreateTokens||0,h=(e.inputTokens||0)/1e6*r.input+(e.outputTokens||0)/1e6*r.output+(e.cacheReadTokens||0)/1e6*r.cacheRead+(e.cacheCreateTokens||0)/1e6*r.cacheCreate,d=i/1e6*r.input+c/1e6*r.output+a/1e6*r.cacheRead+u/1e6*r.cacheCreate;return h+d*an}cost(e,t){return J.calculateCost(e,t,this.pricing)}record(e,t,n,s,r,i,c,a,u){let h=this.today(),d=h.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};d.tasks++,d.totalDuration+=t,c&&(d.model=c);let g=0,p=0,k=0,f=0,w=0,I=0,x=0,R=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>it?(w=n.inputTokens,I=n.outputTokens,x=n.cacheReadTokens,R=n.cacheCreateTokens):(g=n.inputTokens,p=n.outputTokens,k=n.cacheReadTokens,f=n.cacheCreateTokens):s!==void 0&&r!==void 0&&(g=Math.ceil(s/4),p=Math.ceil(r/4)),d.inputTokens+=g,d.outputTokens+=p,d.cacheReadTokens+=k,d.cacheCreateTokens+=f,d.tier2InputTokens=(d.tier2InputTokens||0)+w,d.tier2OutputTokens=(d.tier2OutputTokens||0)+I,d.tier2CacheReadTokens=(d.tier2CacheReadTokens||0)+x,d.tier2CacheCreateTokens=(d.tier2CacheCreateTokens||0)+R,i&&d.errors++,d.byChannel||(d.byChannel={});let $=(a||"other").toLowerCase(),T=d.byChannel[$]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};T.tasks++,T.totalDuration+=t,T.inputTokens+=g,T.outputTokens+=p,T.cacheReadTokens+=k,T.cacheCreateTokens+=f,T.tier2InputTokens+=w,T.tier2OutputTokens+=I,T.tier2CacheReadTokens+=x,T.tier2CacheCreateTokens+=R,i&&T.errors++,d.byChannel[$]=T,u&&(d.sessionKeys||(d.sessionKeys=[]),d.sessionKeys.includes(u)||(d.sessionKeys.push(u),d.sessionKeys.length>rt&&d.sessionKeys.splice(0,d.sessionKeys.length-rt))),h.agents[e]=d,this.save(h)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(q(t))try{return this.cache=JSON.parse(Z(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!q(t))return null;try{return JSON.parse(Z(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let s=0,r=0,i=0,c=0,a=0,u=0,h="",d=0,g={},p={},k={};for(let[f,w]of Object.entries(n.agents)){let I=this.cost(w);g[f]=I,s+=w.tasks,r+=(w.inputTokens||0)+(w.tier2InputTokens||0),i+=(w.outputTokens||0)+(w.tier2OutputTokens||0),c+=(w.cacheReadTokens||0)+(w.tier2CacheReadTokens||0),a+=(w.cacheCreateTokens||0)+(w.tier2CacheCreateTokens||0),u+=I,I>d&&(d=I,h=f);let x=w.sessionKeys?.length||0;p[f]={sessions:x,avgTasksPerSession:x>0?w.tasks/x:w.tasks};for(let[R,$]of Object.entries(w.byChannel||{})){let T=this.cost($,w.model);k[R]=(k[R]||0)+T}}return{date:t,totalTasks:s,totalInput:r,totalOutput:i,totalCacheRead:c,totalCacheCreate:a,totalCost:u,topAgent:h,topCost:d,agentCosts:g,agentSessionStats:p,byChannel:k}}appendToTokenCosts(e,t){let n=t||G(process.cwd(),".agentx/TOKEN_COSTS.md"),s=u=>u<.01?u.toFixed(4):u.toFixed(2),r=u=>u>=1e6?`${(u/1e6).toFixed(1)}M`:u>=1e3?`${(u/1e3).toFixed(0)}K`:String(u),i=Object.entries(e.agentCosts).sort(([,u],[,h])=>h-u).map(([u,h])=>{let d=e.agentSessionStats[u],g=d&&d.sessions>0?` (${d.sessions}s, ${d.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${u}: $${s(h)}${g}`}).join(", "),c=Object.entries(e.byChannel).sort(([,u],[,h])=>h-u).map(([u,h])=>`${u}: $${s(h)}`).join(", "),a=`| ${e.date} | ${e.totalTasks} | ${r(e.totalInput)} | ${r(e.totalOutput)} | ${r(e.totalCacheRead)} | ${r(e.totalCacheCreate)} | $${s(e.totalCost)} | ${i} | ${c} |`;q(n)?rn(n,a+`
|
|
13
|
-
`):st(n,`# Token Costs
|
|
14
|
-
|
|
15
|
-
Daily token cost tracking. Auto-appended at midnight (Africa/Tunis).
|
|
16
|
-
Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
17
|
-
|
|
18
|
-
| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
|
|
19
|
-
|------|-------|-------|--------|---------|---------|------|-----------|-------------|
|
|
20
|
-
`+a+`
|
|
21
|
-
`)}hasTokenCostsEntry(e,t){let n=t||G(process.cwd(),".agentx/TOKEN_COSTS.md");if(!q(n))return!1;try{let s=Z(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(s)}catch{return!1}}lastTokenCostsDate(e){let t=e||G(process.cwd(),".agentx/TOKEN_COSTS.md");if(!q(t))return null;try{let s=Z(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(s.length===0)return null;let r=s.map(i=>i.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(i=>!!i);return r.sort(),r[r.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,s=[],r=this.lastTokenCostsDate(t.filePath),i=[],c=new Date(`${e}T00:00:00Z`);for(let a=0;a<n;a++){let u=c.toISOString().slice(0,10);if(r&&u<=r)break;i.push(u),c.setUTCDate(c.getUTCDate()-1)}i.reverse();for(let a of i){if(this.hasTokenCostsEntry(a,t.filePath))continue;let u=this.generateDailyReport(a);!u||u.totalTasks===0||(this.appendToTokenCosts(u,t.filePath),s.push(a))}return s}summary(e=7){let t=0,n=0,s=0,r=0,i=0,c=0,a=0,u={},h={};for(let k=0;k<e;k++){let f=new Date(Date.now()-k*864e5).toISOString().slice(0,10),w=this.getDate(f);if(w)for(let[I,x]of Object.entries(w.agents)){let R=this.cost(x);t+=x.tasks;let $=(x.inputTokens||0)+(x.tier2InputTokens||0),T=(x.outputTokens||0)+(x.tier2OutputTokens||0),v=(x.cacheReadTokens||0)+(x.tier2CacheReadTokens||0),y=(x.cacheCreateTokens||0)+(x.tier2CacheCreateTokens||0);n+=$,s+=T,r+=v,i+=y,c+=x.errors,a+=R;let C=u[I]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};C.tasks+=x.tasks,C.input+=$,C.output+=T,C.cacheRead+=v,C.cacheCreate+=y,C.total=C.input+C.output+C.cacheRead+C.cacheCreate,C.totalDuration+=x.totalDuration,C.avgDuration=C.totalDuration/C.tasks,C.cost+=R,C.sessions+=x.sessionKeys?.length||0,x.model&&(C.model=x.model),u[I]=C;for(let[O,X]of Object.entries(x.byChannel||{})){let ne=this.cost(X,x.model),N=h[O]||{tasks:0,cost:0};N.tasks+=X.tasks,N.cost+=ne,h[O]=N}}}let d=n+s+r+i,g=r+i>0?r/(r+i):0,p={};for(let[k,f]of Object.entries(u))p[k]={sessions:f.sessions,avgTasksPerSession:f.sessions>0?f.tasks/f.sessions:f.tasks};return{totalTasks:t,totalTokens:d,totalInput:n,totalOutput:s,totalCacheRead:r,totalCacheCreate:i,cacheHitRatio:g,totalErrors:c,totalCost:a,byAgent:u,byChannel:h,sessionStats:p}}filePath(e){return G(this.dir,`${e}.json`)}save(e){try{st(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function dn(){let o=JSON.parse(JSON.stringify(ot));try{let e=G(process.cwd(),un);if(!q(e))return o;let t=JSON.parse(Z(e,"utf-8"));for(let[n,s]of Object.entries(t))o[n]||(o[n]={input:0,output:0,cacheRead:0,cacheCreate:0}),Object.assign(o[n],s)}catch{}return o}var ln={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,memory:600,history:1200,"cross-chat":800,wiki:1e3}},ct=4;function ut(o,e=ln){let t=gn(o,e);t.sort((i,c)=>i.priority-c.priority);let n=[],s=0,r=e.totalBudget*ct;for(let i of t){if(!i.content)continue;let c=i.maxTokens*ct,a=i.content.length>c?i.content.slice(0,c)+"...":i.content;if(s+a.length>r){let u=r-s;u>100&&n.push(a.slice(0,u)+"...");break}n.push(a),s+=a.length}return n.join(`
|
|
22
|
-
|
|
23
|
-
`)}function gn(o,e){let t=(i,c)=>e.layerBudgets?.[i]??c,n=[];if(n.push(hn(o,t("channel",200))),n.push(mn(o,t("scope",200))),o.landscape&&n.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:o.landscape,tags:["landscape","world-model"]}),o.systemPrompt&&n.push({name:"identity",priority:4,maxTokens:t("identity",200),content:o.systemPrompt.split(`
|
|
24
|
-
`)[0],tags:["identity",o.agentId]}),o.bootstrapContext&&n.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:o.bootstrapContext,tags:["bootstrap","identity","personality"]}),o.references&&n.push({name:"references",priority:4.7,maxTokens:t("references",500),content:o.references,tags:["references","verified","deterministic"]}),o.intent&&o.intent.path.length>0){let i=[`[Intent path: ${o.intent.pathLabel}${o.intent.status==="pending"?" (pending approval)":""}]`],c=o.intent.path[o.intent.path.length-1],a=o.intent.axes?.[c];if(a&&Object.keys(a).length){let u=Object.entries(a).map(([h,d])=>` ${h}: ${d}`).join(`
|
|
25
|
-
`);i.push(u)}o.intent.leaf?.input&&i.push(` input: ${o.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
|
|
26
|
-
`),tags:["intent",...o.intent.path]})}else{let i=pn(o.message);i.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let s=[];o.replyToText&&s.push(`[Replying to]: ${o.replyToText.slice(0,300)}`),o.mediaPath&&(s.push(`[Attached file: ${o.mediaPath}]`),s.push(`[File type: ${o.mediaType||"unknown"}]`),o.mediaType?.startsWith("image/")?s.push("Please view this image and respond to it."):o.mediaType?.startsWith("audio/")&&s.push("Please transcribe this audio and respond.")),o.issueMR&&s.push(`[${o.issueMR.type} #${o.issueMR.iid}: ${o.issueMR.title}]`),s.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:s.join(`
|
|
27
|
-
`),tags:["artifacts",...o.mediaType?["media"]:[]]}),o.skillInjection&&n.push({name:"skills",priority:6.2,maxTokens:t("skills",2e3),content:o.skillInjection,tags:["skills","auto-inject"]}),o.patternContext&&n.push({name:"patterns",priority:6.3,maxTokens:t("patterns",400),content:o.patternContext,tags:["patterns","behavioral","self-improving"]}),o.memoryContext&&n.push({name:"memory",priority:6.5,maxTokens:t("memory",600),content:o.memoryContext,tags:["memory","persistent"]});let r=o.groupHistory||o.sessionHistory;if(r&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:r,tags:["history","conversation"]}),o.crossChatContext&&n.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:o.crossChatContext,tags:["history","cross-chat"]}),o.longMemoryRecall&&n.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:o.longMemoryRecall,tags:["history","long-memory"]}),o.handoverNote){let i=[`[Handover] You are taking over this conversation from ${o.handoverNote.fromAgent}.`];o.handoverNote.summary&&i.push(`Operator summary: ${o.handoverNote.summary}`),i.push(`Handover time: ${o.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
|
|
28
|
-
`),tags:["handover",o.handoverNote.fromAgent]})}return o.wikiContext&&n.push({name:"wiki",priority:8,maxTokens:t("wiki",1e3),content:o.wikiContext,tags:["wiki","knowledge"]}),n}function hn(o,e){let t=[`Channel: ${o.channel}`];o.chatId&&t.push(`Chat ID: ${o.chatId} (use this verbatim in /recall, /send)`);let n=[],s=[o.channel];switch(o.channel){case"telegram":o.agentHandle&&t.push(`Your handle: ${o.agentHandle}`),t.push(`From: ${o.sender}`),o.senderId&&t.push(`Telegram user ID: ${o.senderId}`),o.senderUsername&&t.push(`Username: @${o.senderUsername}`),n.push("Format responses using Telegram-compatible markdown"),n.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),n.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${o.sender}`),n.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),n.push("No rich formatting \u2014 plain text only"),n.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${o.sender}`),n.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),n.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),n.push("Do NOT delegate to other agents"),n.push("Reference issues with #IID and merge requests with !IID"),n.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),n.push("Never narrate what you are about to do \u2014 just do it and report the result"),s.push("code-review");break;case"discord":t.push(`From: ${o.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:o.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),s.push("webhook","automated"))}return n.length&&(t.push(""),t.push("[Rules]"),t.push(...n.map(r=>`- ${r}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
29
|
-
`),tags:s,rules:n}}function mn(o,e){let t=[],n=[];if(o.channelScope==="group"&&o.groupName?(t.push(`Group: ${o.groupName}`),n.push("group",o.groupName)):o.channelScope==="project"&&o.projectPath?(t.push(`Project: ${o.projectPath}`),n.push("project",o.projectPath)):o.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),o.channelMeta){let s=o.channelMeta;if(s.agents?.length&&(t.push(`[Verified bots in this chat: ${s.agents.map(r=>r.handle||r.name||r.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),s.project&&t.push(`Project: ${s.project}`),s.issue&&t.push(`${s.issue.type} #${s.issue.iid}${s.issue.title?`: ${s.issue.title}`:""}`),s.facts?.length)for(let r of s.facts)t.push(`\u2022 ${r}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
30
|
-
`),tags:n}}function pn(o){let e=[],t=o.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}import{readFileSync as fn,writeFileSync as dt,appendFileSync as yn,mkdirSync as bn,existsSync as lt}from"fs";import{resolve as ve}from"path";var gt=200,Tn=7,le=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=ve(e,".agentx/memory"),lt(this.memoryDir)||bn(this.memoryDir,{recursive:!0})}filePath(e){return ve(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};yn(this.filePath(e),JSON.stringify(n)+`
|
|
31
|
-
`)}getAll(e){let t=this.filePath(e);if(!lt(t))return[];try{return fn(t,"utf-8").split(`
|
|
32
|
-
`).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null)}catch{return[]}}findRelevant(e,t,n=8){let s=this.getAll(t);if(s.length===0)return[];let r=s.map(p=>`${p.keywords.join(" ")} ${p.content}`),i=ve(this.memoryDir,`${t}_bm25_cache.json`),c=ie(r,i),a=oe(e,c),u=new Map(a.map(p=>[p.docIndex,p.score])),d=s.map((p,k)=>{let f=u.get(k)??0;return p.category==="secret"&&(f+=2),p.category==="commitment"&&(f+=1),{memory:p,score:f}}).filter(p=>p.score>0);if(d.length===0)return s.slice(-n);let g=d.sort((p,k)=>k.score-p.score).slice(0,n).map(p=>p.memory);if(g.length>0)try{this.recordAccess(t,g.map(p=>p.id))}catch{}return g}buildContext(e){if(e.length===0)return"";let t=["[Agent Memory \u2014 persistent facts from past conversations]"],n=t[0].length;for(let s of e){let i=!s.source.chatId.startsWith("-")&&/^\d+$/.test(s.source.chatId)?"DM":s.source.chatId,c=`- [${s.category}] ${s.content} (${i}, ${s.source.date})`;if(n+c.length>2400)break;t.push(c),n+=c.length}return t.push("[End Memory]"),t.join(`
|
|
33
|
-
`)}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),s=new Set(t),r=!1;for(let i of n)if(s.has(i.id)){i.accessCount=(i.accessCount||0)+1,i.lastAccessed=new Date().toISOString();let c=i.intervalDays||1;i.intervalDays=Math.min(c*2,30),i.nextReview=new Date(Date.now()+i.intervalDays*864e5).toISOString(),r=!0}r&&dt(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
34
|
-
`)+`
|
|
35
|
-
`)}getDueForReview(e,t=5){let n=this.getAll(e),s=Date.now();return n.filter(r=>r.category==="task-state"?!1:r.nextReview?new Date(r.nextReview).getTime()<=s:!0).sort((r,i)=>!r.nextReview&&i.nextReview?-1:r.nextReview&&!i.nextReview?1:r.nextReview&&i.nextReview?new Date(r.nextReview).getTime()-new Date(i.nextReview).getTime():(r.accessCount||0)-(i.accessCount||0)).slice(0,t)}buildRecallContext(e){let t=this.getDueForReview(e,5);if(t.length===0)return"";let n=["[Memory Recall \u2014 facts due for review, verify they are still accurate]"];for(let s of t){let r=Math.round((Date.now()-new Date(s.createdAt).getTime())/864e5);n.push(`- [${s.category}] ${s.content} (${r}d old, accessed ${s.accessCount||0}x)`)}return n.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),n.join(`
|
|
36
|
-
`)}hasSimilar(e,t){let n=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(i=>i.length>3);return n.some(i=>{let c=i.content.toLowerCase();return r.filter(u=>c.includes(u)).length>=r.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let n=Date.now(),s=Tn*24*60*60*1e3;t=t.filter(i=>i.category==="task-state"&&i.expiresAt?new Date(i.expiresAt).getTime()>n:i.category==="task-state"&&!i.expiresAt?n-new Date(i.createdAt).getTime()<s:!0),t.length>gt&&(t=t.slice(-gt));let r=this.filePath(e);dt(r,t.map(i=>JSON.stringify(i)).join(`
|
|
37
|
-
`)+`
|
|
38
|
-
`)}};import{existsSync as V,mkdirSync as xn,readdirSync as kn,readFileSync as wn,unlinkSync as Ie,writeFileSync as ge}from"fs";import{resolve as H}from"path";var U=["user","feedback","project","reference"],he=class{baseDir;constructor(e={}){let t=e.baseDir??H(process.cwd(),".agentx");this.baseDir=H(t,"agent-memory")}dirFor(e){let t=Re(e),n=H(this.baseDir,t);return xn(n,{recursive:!0}),n}fileFor(e,t,n){return H(this.dirFor(e),`${t}_${Re(n)}.md`)}indexPath(e){return H(this.dirFor(e),"MEMORY.md")}save(e){if(!U.includes(e.type))throw new Error(`invalid memory type: ${e.type}`);if(!e.name.trim())throw new Error("memory name is required");if(!e.description.trim())throw new Error("memory description is required");let t=this.fileFor(e.agentId,e.type,e.name),n=new Date().toISOString(),s=n,r=ee(t);if(r){let c=$e(r);c&&(s=c.createdAt)}let i={name:Re(e.name),type:e.type,description:e.description.trim(),body:e.body.trimEnd(),createdAt:s,updatedAt:n};return ge(t,Sn(i)),this.rewriteIndex(e.agentId),i}get(e,t){for(let n of U){let s=this.fileFor(e,n,t);if(!V(s))continue;let r=$e(ee(s)??"");if(r)return r}return null}list(e){let t=this.dirFor(e);if(!V(t))return[];let n=[];for(let s of kn(t,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name==="MEMORY.md")continue;let r=$e(ee(H(t,s.name))??"");r&&n.push(r)}return n.sort((s,r)=>{let i=U.indexOf(s.type),c=U.indexOf(r.type);return i!==c?i-c:s.name.localeCompare(r.name)})}remove(e,t){let n=!1;for(let s of U){let r=this.fileFor(e,s,t);V(r)&&(Ie(r),n=!0)}return n&&this.rewriteIndex(e),n}indexMarkdown(e){let t=this.indexPath(e);return ee(t)??""}syncToWorkspace(e,t){if(!t)return;let n=this.indexMarkdown(e).trim(),s=H(t,".agentx-memory.md");n?ge(s,n+`
|
|
39
|
-
`):V(s)&&Ie(s);let r=H(t,"CLAUDE.md"),i="<!-- AGENTX-MEMORY-START \u2014 auto-managed by agentx; edit via `agentx memory` -->",c="<!-- AGENTX-MEMORY-END -->",a=n?`${i}
|
|
40
|
-
${n}
|
|
41
|
-
${c}`:"",u=ee(r)??"",h=u.indexOf(i),d=u.indexOf(c),g;if(h>=0&&d>h){let p=u.slice(0,h).replace(/\n+$/,""),k=u.slice(d+c.length).replace(/^\n+/,"");g=a?[p,a,k].filter(Boolean).join(`
|
|
42
|
-
|
|
43
|
-
`)+`
|
|
44
|
-
`:[p,k].filter(Boolean).join(`
|
|
45
|
-
|
|
46
|
-
`)+(p||k?`
|
|
47
|
-
`:"")}else if(a)g=u?u.replace(/\n+$/,"")+`
|
|
48
|
-
|
|
49
|
-
`+a+`
|
|
50
|
-
`:a+`
|
|
51
|
-
`;else return;ge(r,g)}rewriteIndex(e){let t=this.list(e);if(t.length===0){let r=this.indexPath(e);V(r)&&Ie(r);return}let n={user:[],feedback:[],project:[],reference:[]};for(let r of t)n[r.type].push(r);let s=[];s.push(`# Memory \u2014 ${e}`,""),s.push("This is the agent's experiential memory: user preferences,"),s.push("feedback, project-specific context, and external references."),s.push("Updated via `agentx memory` CLI or by the agent itself.");for(let r of U){let i=n[r];if(i.length){s.push("",`## ${In(r)}`,"");for(let c of i)s.push(`- **${c.name}** \u2014 ${c.description} _(updated ${c.updatedAt.slice(0,10)})_`)}}s.push(""),ge(this.indexPath(e),s.join(`
|
|
52
|
-
`))}};function Sn(o){return["---",`name: ${o.name}`,`description: ${Cn(o.description)}`,`type: ${o.type}`,`created: ${o.createdAt}`,`updated: ${o.updatedAt}`,"---",""].join(`
|
|
53
|
-
`)+o.body+`
|
|
54
|
-
`}function $e(o){if(!o.startsWith(`---
|
|
55
|
-
`))return null;let e=o.indexOf(`
|
|
56
|
-
---
|
|
57
|
-
`,4);if(e<0)return null;let t=o.slice(4,e),n=o.slice(e+5).replace(/^\n+/,"").trimEnd(),s={};for(let r of t.split(`
|
|
58
|
-
`)){let i=r.indexOf(":");if(i<0)continue;let c=r.slice(0,i).trim(),a=vn(r.slice(i+1).trim());s[c]=a}return!s.name||!s.type||!s.description||!U.includes(s.type)?null:{name:s.name,type:s.type,description:s.description,body:n,createdAt:s.created??"",updatedAt:s.updated??s.created??""}}function Cn(o){return/[:#\n]/.test(o)?`"${o.replace(/"/g,'\\"')}"`:o}function vn(o){return o.startsWith('"')&&o.endsWith('"')&&o.length>=2?o.slice(1,-1).replace(/\\"/g,'"'):o}function Re(o){return o.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"unnamed"}function In(o){return o.charAt(0).toUpperCase()+o.slice(1)}function ee(o){try{return wn(o,"utf-8")}catch{return null}}var me=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,n){return`${e}:${t}:${n}`}getOrCreate(e,t,n){let s=this.key(e,t,n);return this.queues.has(s)||this.queues.set(s,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(s)}setMode(e,t,n,s){this.getOrCreate(e,t,n).mode=s}onFlush(e,t,n,s){this.getOrCreate(e,t,n).onFlush=s}isBusy(e,t,n){return this.getOrCreate(e,t,n).running}markRunning(e,t,n){let s=this.getOrCreate(e,t,n);return s.running?!1:(s.running=!0,!0)}enqueue(e,t,n,s){let r=this.getOrCreate(e,t,n);if(!r.running)return null;switch(r.mode){case"drop":return"drop";case"collect":case"followup":return r.pending.push(s),r.mode}}async markDone(e,t,n){let s=this.getOrCreate(e,t,n);if(s.running=!1,s.pending.length===0)return[];let r=[...s.pending];switch(s.pending=[],s.mode){case"collect":{let i={text:r.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
|
|
59
|
-
`),sender:r[r.length-1].sender,timestamp:Date.now(),channel:r[0].channel,chatId:r[0].chatId,originalContext:r[r.length-1].originalContext};return s.onFlush&&await s.onFlush([i]),[i]}case"followup":return s.onFlush&&await s.onFlush(r),r;case"drop":return[];default:return r}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let s=this.key(e,t,n);this.queues.delete(s)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as $n,writeFileSync as ht,appendFileSync as Rn,mkdirSync as An,existsSync as mt}from"fs";import{resolve as Ae}from"path";var pt=50,Mn="claude-haiku-4-20250514",Dn=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
|
|
60
|
-
|
|
61
|
-
Extract patterns like:
|
|
62
|
-
- "When asked about X, the approach that works is Y"
|
|
63
|
-
- "User prefers Z style of communication"
|
|
64
|
-
- "For deployment tasks, always check A before doing B"
|
|
65
|
-
- "This codebase uses pattern X, so generate code following X"
|
|
66
|
-
|
|
67
|
-
SKIP:
|
|
68
|
-
- Factual information (names, dates, URLs)
|
|
69
|
-
- Routine task completions
|
|
70
|
-
- Greetings or small talk
|
|
71
|
-
|
|
72
|
-
Output a JSON array:
|
|
73
|
-
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
74
|
-
|
|
75
|
-
If nothing worth extracting, output: []`,pe=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Ae(e,".agentx/patterns"),mt(this.patternsDir)||An(this.patternsDir,{recursive:!0})}filePath(e){return Ae(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!mt(t))return[];try{return $n(t,"utf-8").split(`
|
|
76
|
-
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};Rn(this.filePath(e),JSON.stringify(n)+`
|
|
77
|
-
`)}findRelevant(e,t,n=5){let s=this.getAll(t);if(s.length===0)return[];let r=s.map(h=>`${h.context} ${h.pattern}`),i=Ae(this.patternsDir,`${t}_bm25_cache.json`),c=ie(r,i),u=oe(e,c).slice(0,n).map(h=>s[h.docIndex]).filter(h=>h.confidence>=.3);return u.length>0&&this.recordAccess(t,u.map(h=>h.id)),u}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let n of e)t.push(`- ${n.pattern} (context: ${n.context}, confidence: ${Math.round(n.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
|
|
78
|
-
`)}hasSimilar(e,t){let n=this.getAll(e),s=t.toLowerCase().split(/\s+/).filter(r=>r.length>3);return n.some(r=>{let i=r.pattern.toLowerCase();return s.filter(a=>i.includes(a)).length>=s.length*.6})}recordAccess(e,t){let n=this.getAll(e),s=new Set(t),r=!1;for(let i of n)s.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),r=!0);r&&ht(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
79
|
-
`)+`
|
|
80
|
-
`)}prune(e){let t=this.getAll(e);t.length<=pt||(t.sort((n,s)=>s.confidence*s.accessCount-n.confidence*n.accessCount),t=t.slice(0,pt),ht(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
81
|
-
`)+`
|
|
82
|
-
`))}};async function ft(o,e,t,n,s){if(e.length<30&&t.length<100)return;let{createProvider:r}=await import("./providers-WVCMIW67.js"),a=(await r("claude").generate([{role:"system",content:Dn},{role:"user",content:`User: ${e.slice(0,500)}
|
|
83
|
-
|
|
84
|
-
Agent: ${t.slice(0,1e3)}`}],{model:Mn,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!a)return;let u=JSON.parse(a[0]);if(!(!Array.isArray(u)||u.length===0)){for(let h of u)s.hasSimilar(o,h.pattern)||s.addPattern(o,{agentId:o,pattern:h.pattern,context:h.context,confidence:h.confidence||.5,source:n});Math.random()<.05&&s.prune(o)}}import{EventEmitter as Pn}from"events";var De=class{inner=new Pn;constructor(){this.inner.setMaxListeners(50)}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){return this.inner.emit(e,t)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this}},Me;function Q(){return Me||(Me=new De),Me}import{readFileSync as On}from"fs";import{homedir as _n}from"os";import{join as En}from"path";var te=null,Nn=6e4;function Hn(){try{let o=En(_n(),".claude.json"),e=On(o,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function jn(o,e=Date.now()){if(!o)return{available:!0,checkedAt:e,unknown:!0};let t=typeof o.cachedExtraUsageDisabledReason=="string"?o.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function Fn(o=!1){let e=Date.now();return!o&&te&&e-te.checkedAt<Nn||(te=jn(Hn(),e)),te}function yt(o){let e=Fn();return e.available||o?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var bt={warnRatio:.8},D={...bt},Ln=5*60*60*1e3,Un=60*60*1e3,W=[];function Tt(o){D={...bt,...o||{}}}function xt(o){let e=o-Ln,t=0;for(;t<W.length&&W[t]<e;)t++;t>0&&W.splice(0,t)}function kt(o=Date.now()){xt(o),W.push(o)}function wt(o=Date.now()){xt(o);let e=o-Un,t=0;for(let r=W.length-1;r>=0&&W[r]>=e;r--)t++;let n=W.length,s={lastHour:t,last5h:n,maxPerHour:D.maxPerHour,maxPer5h:D.maxPer5h};return D.maxPerHour&&D.maxPerHour>0&&(s.hourlyRatio=t/D.maxPerHour),D.maxPer5h&&D.maxPer5h>0&&(s.fiveHourRatio=n/D.maxPer5h),s}function St(o,e=Date.now()){let t=wt(e);return o?null:D.maxPerHour&&t.lastHour>=D.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${D.maxPerHour} in the last hour. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPerHour in DaemonConfig if this is a false positive.`,usage:t}:D.maxPer5h&&t.last5h>=D.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${D.maxPer5h} in the last 5h. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPer5h in DaemonConfig if this is a false positive.`,usage:t}:null}function Ct(o=Date.now()){let e=wt(o),t=D.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=t&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=t&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of cap)`:null}var Pe=new Map;function vt(o,e,t){return t?`${o}:${e}:${t}`:`${o}:${e}`}function It(o,e,t,n=Date.now()){let s=Pe.get(o);s||(s={key:o,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},Pe.set(o,s)),s.samples+=1,s.baseline=.2*e+(1-.2)*s.baseline,s.current=e,s.peak=Math.max(s.peak,e),s.lastAt=n,s.ring.push({key:o,timestamp:n,total:e,parts:t}),s.ring.length>100&&s.ring.shift()}function $t(o){let e=Pe.get(o);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let n=e.current/e.baseline;return`prompt-size drift for ${o}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as E,mkdirSync as Wn,readdirSync as _,readFileSync as Oe,rmSync as Bn,writeFileSync as Kn}from"fs";import{resolve as A}from"path";var Mt;function sr(o){Mt=o}function rr(){return Mt}var Rt=64*1024,qn=5*60*1e3,z=".agentx/task-history",Gn=30;function _e(o,e=800){return o.length<=e?o:o.slice(0,e)+` \u2026[+${o.length-e} chars]`}function Jn(o,e){let t=0;try{t=o.listArticles(e).length}catch{return""}if(t===0)return"";let n=A(o.baseDir,"_index.md");if(!E(n))return"";let s=process.argv[1]||"dist/cli.js",r=o.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 cross-agent source of truth]",`A curated wiki with ${t} article${t===1?"":"s"} grouped by type: person, project, place, concept, event, decision, pattern.`,"","The wiki is the canonical source for: who people are (team, clients, agents), past events (incidents, deploys), decisions and their reasoning, documented procedures, patterns.","","BEFORE you grep the workspace, search memory, or answer from your own prior context \u2014 if the question is about who / what happened / what we decided / how we do X, call:",` node ${s} wiki query "the user's question" --dir ${r} --agent ${e}`,"","It walks the catalog + wikilink graph and returns a cited answer. Your workspace memory is local to you; the wiki is shared and authoritative. Prefer the wiki for institutional questions; prefer your workspace for code-level questions.","[End Institutional Wiki]"].join(`
|
|
85
|
-
`)}function Qn(){let o="";return e=>{if(!e||typeof e!="object")return"";let t=e.type;if(t==="system"&&e.subtype==="init"){let n=e.model?` model=${e.model}`:"",s=e.session_id?` session=${e.session_id.slice(0,8)}`:"";return`\xB7 init${n}${s}
|
|
86
|
-
`}if(t==="assistant"&&e.message?.content){let n="";for(let s of e.message.content)if(s.type==="text"&&typeof s.text=="string")s.text.length>o.length&&(n+=s.text.slice(o.length),o=s.text);else if(s.type==="thinking"&&typeof s.thinking=="string")n+=`
|
|
87
|
-
\u{1F4AD} ${_e(s.thinking,600)}
|
|
88
|
-
`;else if(s.type==="tool_use"){let r=s.name||"tool",i=s.input?_e(JSON.stringify(s.input),400):"";n+=`
|
|
89
|
-
\u2192 ${r}(${i})
|
|
90
|
-
`}return n}if(t==="user"&&e.message?.content){let n="";for(let s of e.message.content)if(s.type==="tool_result"){let r=Array.isArray(s.content)?s.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof s.content=="string"?s.content:"",i=s.is_error?"\u2190 [error] ":"\u2190 ";n+=`${i}${_e(r,800)}
|
|
91
|
-
`}return n}return t==="result"?`\xB7 done${e.duration_ms?` (${Math.round(e.duration_ms/1e3)}s)`:""}
|
|
92
|
-
`:""}}var At=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new he;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;messageQueue;classifier;graphStore;handoverStore=new Ke;activeSouls=new Map;taskOutputs=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new ue(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Be(void 0,void 0,"unified"),this.memoryStore=new le,this.patternStore=new pe,this.rateLimiter=new de,this.tokenTracker=new J,this.messageQueue=new me,Tt({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Ue({baseDir:A(process.cwd(),e.graph.baseDir),log:(...s)=>t("[graph]",...s)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new We({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...s)=>t("[classifier]",...s)})}for(let[n,s]of Object.entries(e.agents))this.agents.set(n,{id:n,def:s,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let s=this.handoverStore.get(t,n);if(!s||s.toAgent!==e)return;let r=this.handoverStore.consumeSummary(t,n);if(!(!r&&s.summaryConsumedAt))return{fromAgent:s.fromAgent,summary:r||s.summary,at:s.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),s,r=0;for(let[i,c]of this.agents)for(let a of c.def.mentions){if(t.atMentionsOnly&&!a.startsWith("@"))continue;let u=a.toLowerCase();n.includes(u)&&u.length>r&&(s=i,r=u.length)}return s}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[s,r]of this.agents)for(let i of r.def.mentions)if(t.includes(i.toLowerCase())){n.push(s);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async captureRotationMemoAsync(e,t,n,s,r,i){try{let{extractRotationMemo:c}=await import("./rotation-memo-GMTZPMNE.js"),a=await c(t,n);if(!a.memo){this.log(`[${e}] rotation memo skipped (${i}, ${a.reason}, ${a.durationMs}ms)`);return}let u=r.split(/[:@.]/).filter(Boolean).slice(0,4);this.memoryStore.addMemory(e,{agentId:e,category:"fact",content:`[Rotation memo \xB7 ${i}] ${a.memo}`,keywords:["rotation-memo",s,...u],source:{channel:s,chatId:r,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}}),this.log(`[${e}] rotation memo captured (${i}, ${a.durationMs}ms, ${a.memo.length} chars)`)}catch(c){this.log(`rotation memo error: ${c?.message||c}`)}}buildPeerList(e,t){let n=[];for(let[s,r]of this.agents)s!==e&&n.push({name:r.def.name,handle:this.getChannelHandle(s,t),role:r.def.systemPrompt?.split(`
|
|
93
|
-
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(s=>s.startsWith("@")):n.mentions[0]}async execute(e,t){let n=Date.now(),s;try{s=await this.executeInternal(e,t)}catch(r){s={content:"",error:r?.message??String(r)}}if(e.intentRef)try{let r=s.error?/timed out|timeout/i.test(s.error)?"timed-out":"failed":"completed";ze().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:r,durationMs:Date.now()-n,resultSummary:s.error?s.error.slice(0,200):s.content?.slice(0,200)??null})}catch(r){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${r?.message??r}`)}return s}async executeInternal(e,t){let n=this.agents.get(e.agentId);if(!n){if(this.meshFallback){let l=this.meshFallback.directory().find(m=>m.healthy&&m.skills.some(b=>b.id===e.agentId));if(l){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${l.peer}"`);try{let m=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(l.peer,e.message,e.agentId,{timeoutMs:m}),viaMesh:l.peer}}catch(m){return this.log(`[${e.agentId}] mesh fallback to "${l.peer}" failed: ${m?.message??m}`),{content:"",error:`mesh fallback failed: ${m?.message??m}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let s=e.context?.channel||"api",r=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(n.activeTasks>=n.def.maxConcurrent)if(s==="api"){let l=Date.now(),m=25*6e4,b=500;for(;n.activeTasks>=n.def.maxConcurrent;){if(Date.now()-l>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(m/6e4)}m`};await new Promise(S=>setTimeout(S,b))}}else{let l=n.def.queueMode||"collect",m=this.messageQueue.enqueue(e.agentId,s,r,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:s,chatId:r,originalContext:e.context});if(m==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(m){let b=this.messageQueue.pendingCount(e.agentId,s,r);return this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${b})`),{content:"",error:`__queued__:${m}:${b}`}}}let i=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(l,m)=>{this.log(`[${e.agentId}] ${l} \u2014 queued, resumes in ~${Math.max(1,Math.round(m/1e3))}s`)}});if(!i.ok)return this.log(`[${e.agentId}] ${i.reason}`),{content:"",error:i.reason};n.activeTasks++,n.totalTasks++,n.lastActive=new Date;let c={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};n.runningTasks.push(c);let a={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(c.id,a);let u=l=>{if(l){a.buffer+=l,a.buffer.length>Rt&&(a.buffer=a.buffer.slice(a.buffer.length-Rt));for(let m of a.subscribers)try{m(l)}catch{}}},h;if(t){let l=Qn();h=m=>{let b=l(m);b&&u(b)}}this.messageQueue.markRunning(e.agentId,s,r),this.log(`[${e.agentId}] executing task (${n.activeTasks}/${n.def.maxConcurrent})`);let d=e.context?.channel||"api",g=e.context?.chatId||e.context?.group||e.context?.sender||"default",p=e.context?.sender||"User";await this.sessions.seedIfEmpty(e.agentId,d,g),this.sessions.addUserMessage(e.agentId,d,g,p,e.message);let k=Date.now();Q().emit("task:started",{agentId:e.agentId,channel:d,chatId:g,messagePreview:(e.message||"").slice(0,200),at:new Date(k).toISOString()});let f;if(this.classifier&&d!=="a2a")try{f=await this.classifier.classify({text:e.message,channel:d,sender:e.context?.sender,agentId:e.agentId})||void 0}catch(l){this.log(`[classifier] classify failed for ${e.agentId}: ${l?.message||l}`)}let w=this.wikiHub.getAgentWiki(e.agentId),I=Jn(w,e.agentId),x=this.memoryStore.findRelevant(e.message,e.agentId,8),R=this.memoryStore.buildContext(x),$=this.patternStore.findRelevant(e.message,e.agentId,5),T=this.patternStore.buildContext($),v="";try{let{loadLocalSkills:l,getAutoInjectSkills:m}=await import("./loader-5CA3O5GM.js"),b=await l(n.def.workspace);v=m(b,e.message)}catch{}let y=n.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,d,g):void 0;if(y&&this.sessions.isSessionStale(e.agentId,d,g)&&(this.log(`[${e.agentId}] session stale for ${d}:${g}, starting fresh`),this.captureRotationMemoAsync(e.agentId,n.def,y,d,g,"stale"),this.sessions.clearClaudeSessionId(e.agentId,d,g),Q().emit("session:rotated",{agentId:e.agentId,channel:d,chatId:g,reason:"stale",at:new Date().toISOString()}),y=void 0),y&&this.sessions.shouldRotateByTierTwo(e.agentId,d,g)){let l=this.sessions.getLastTurnInputTokens(e.agentId,d,g);this.log(`[${e.agentId}] tier-2 rotation for ${d}:${g} (last turn: ${l} input tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),this.captureRotationMemoAsync(e.agentId,n.def,y,d,g,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,d,g),Q().emit("session:rotated",{agentId:e.agentId,channel:d,chatId:g,reason:"tier-2",lastTurnInputTokens:l,at:new Date().toISOString()}),y=void 0}if(y&&this.sessions.shouldRotateByTurns(e.agentId,d,g)){let l=this.sessions.getTurnCount(e.agentId,d,g);this.log(`[${e.agentId}] max-turns rotation for ${d}:${g} (${l} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),this.captureRotationMemoAsync(e.agentId,n.def,y,d,g,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,d,g),Q().emit("session:rotated",{agentId:e.agentId,channel:d,chatId:g,reason:"max-turns",at:new Date().toISOString()}),y=void 0}try{let l=await this.sessions.compactIfNeeded(e.agentId,d,g,this.memoryStore);if(l.compacted){let m=l.qualityScore??"?",b=l.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${d}:${g} (quality: ${m}%, ${b} entities lost)`),l.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${l.lostEntities.slice(0,5).join(", ")}`),l.drift){let S=l.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${S.overallScore} (lexicon=${S.lexiconDecay}, tools=${S.toolShift}, semantic=${S.semanticDrift})`),S.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${S.lostWords.slice(0,5).join(", ")}`)}}}catch(l){this.log(`[${e.agentId}] compaction failed (non-fatal): ${l.message}`)}let C=y?void 0:this.sessions.buildHistoryContext(e.agentId,d,g);if(L&&L.cat)try{let m=this.sessions.getSession(e.agentId,d,g).messages,b=m[0],S=m[m.length-1],M=C===void 0?`resume=${y?y.slice(0,8):"?"} (no rebuild)`:`fresh history=${C.length}c/${C.split(`
|
|
94
|
-
`).length}L`,P=`[${e.agentId}] ${d}:${g} ${M} | session.messages=${m.length}`+(m.length>0?` first=${b.timestamp.slice(11,19)}(${b.role}:${(b.content||"").slice(0,40).replace(/\n/g," ")}) last=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")})`:"");L.cat("context",P)}catch(l){L.cat("context",`[${e.agentId}] context-diag error: ${l?.message??l}`)}let O;if(n.def.contextReferences&&!y)try{let l=n.def.workspace,m=this.referencesCache.get(l);if(!m){let[S,M]=await Promise.all([ke(n.def.workspace),we(n.def.workspace)]);if(S.byId.size===0&&M.recipes.length===0){let[P,F]=await Promise.all([ke(process.cwd()),we(process.cwd())]);m={refs:P,recipes:F}}else m={refs:S,recipes:M};this.referencesCache.set(l,m)}let b=Xe({agentId:e.agentId,intentTags:f?.path,message:e.message},m.recipes,m.refs);b.cards.length>0&&(O=Qe(b.cards,500*4)),b.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${b.unresolvedIds.join(", ")}`)}catch(l){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${l?.message||l}`)}let X=this.sessions.getCrossSessionSummary(e.agentId,d,g,e.message),ne,N=nt(e.message);if(N)try{let l=this.sessions.recallTurns({agentId:e.agentId,channel:d,chatId:g,lookbackDays:N.lookbackDays,limit:12});if(l.turns.length>0){let m=[`[Long-memory recall \u2014 last ${N.lookbackDays}d on this chat (cue-triggered)]`],b=[...l.turns].sort((S,M)=>S.ts.localeCompare(M.ts));for(let S of b){let M=S.ts.slice(11,16)+" "+S.day,P=S.role==="user"?S.senderName||"User":S.senderName||"Agent";m.push(`${M} ${P}: ${S.content}`)}l.hasMore&&m.push(`[\u2026${l.totalScanned-l.turns.length}+ older turns available \u2014 call /recall with before=${l.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),ne=m.join(`
|
|
95
|
-
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${N.lookbackDays}d, turns=${l.turns.length}, scanned=${l.totalScanned}`)}}catch(l){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${l.message}`)}let Dt=e.contextStrategy??n.def.contextStrategy??this.config.session.contextStrategy??"layered",Ee,Ne,He=!1;if(Dt==="planner"){try{let{planContext:l}=await import("./context-planner-I7ID7XF3.js"),m=await l({agentId:e.agentId,channel:d,chatId:g,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore});m?(He=!0,Ee=m.sessionHistory,R=m.memoryContext,X=m.crossChatContext,Ne=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(l){this.log(`[${e.agentId}] planner failed (non-fatal): ${l.message} \u2014 falling back to layered (keeping --resume for continuity)`)}He&&y&&(this.sessions.clearClaudeSessionId(e.agentId,d,g),y=void 0)}let fe=`${e.agentId}:${d}:${g}`,se=Je(e.message);se&&(se==="default"?(this.activeSouls.delete(fe),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(fe,se),this.log(`[${e.agentId}] Soul switched to: ${se}`)));let Pt=this.activeSouls.get(fe),Ot=qe(n.def.workspace,Pt),_t=Ge(Ot),Et=this.agentMemory.indexMarkdown(e.agentId),ye=[n.def.systemPrompt||"",_t||"",Et||""].filter(l=>l.trim().length>0).join(`
|
|
96
|
-
|
|
97
|
-
`)||void 0,Nt={channel:d,chatId:g,channelScope:e.context?.group?"group":d==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:n.def.name,agentHandle:this.getChannelHandle(e.agentId,d),systemPrompt:n.def.systemPrompt,sender:p,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:T||void 0,references:O,skillInjection:v||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ee??C,memoryContext:R||void 0,crossChatContext:X||void 0,longMemoryRecall:ne||void 0,wikiContext:I,handoverNote:this.buildHandoverNote(e.agentId,d,g),intent:f?{path:f.path,pathLabel:f.pathLabel,pathId:f.pathId,axes:f.axes,leaf:f.leaf,status:f.status}:void 0,message:e.message},be=ut(Nt),Te=(be?.length??0)+(ye?.length??0)+(e.message?.length??0),re={history:be?.length??0,sysPrompt:ye?.length??0,message:e.message?.length??0},je=vt(e.agentId,d,g);It(je,Te,re);let Fe=$t(je);Fe&&this.log(`[${e.agentId}] ${Fe}`),Te>16e3&&this.log(`[${e.agentId}] large context for ${d}:${g}: ${Te} bytes (history=${re.history}, sysPrompt=${re.sysPrompt}, message=${re.message})`);let Ht={...e,systemPromptAppend:ye},j;try{if(n.def.tier==="claude-code"){let b=!!y,M=[yt(b),St(b)].find(F=>F&&F.abort);if(M){n.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${M.reason}`);let F={content:"",error:M.message,duration:0};if(!t){a.buffer=`[error] ${M.message}`;for(let jt of a.subscribers)try{jt(a.buffer)}catch{}}return j=F,F}kt();let P=Ct();P&&this.log(`[${e.agentId}] ${P}`)}let l=await Ze(n.def,Ht,this.providers,t,be,y,h);j=l;let m=l.usage?at(l.usage):void 0;if(Q().emit("task:completed",{agentId:e.agentId,channel:d,chatId:g,durationMs:Date.now()-k,error:l.error||void 0,inputTokens:m?.inputTokens,outputTokens:m?.outputTokens,cacheReadTokens:m?.cacheReadTokens,cacheCreateTokens:m?.cacheCreateTokens,tier2InputTokens:m?.tier2InputTokens,tier2OutputTokens:m?.tier2OutputTokens,tier2CacheReadTokens:m?.tier2CacheReadTokens,tier2CacheCreateTokens:m?.tier2CacheCreateTokens,at:new Date().toISOString()}),!t&&(l.content||l.error)){let b=l.error?`[error] ${l.error}`:l.content;a.buffer=b;for(let S of a.subscribers)try{S(b)}catch{}}if(l.error)n.errors++,this.log(`[${e.agentId}] error: ${l.error}`);else{if(this.sessions.addAgentMessage(e.agentId,d,g,l.content),l.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,d,g,l.claudeSessionId),l.claudeSessionId&&l.usage&&this.sessions.recordTurnUsage(e.agentId,d,g,l.usage),l.usage){let P=(l.usage.inputTokens||0)+(l.usage.cacheReadTokens||0)+(l.usage.cacheCreateTokens||0);P>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${d}:${g}: ${P} total input tokens (input=${l.usage.inputTokens}, cacheRead=${l.usage.cacheReadTokens}, cacheCreate=${l.usage.cacheCreateTokens}) \u2014 next turn will rotate`)}if(l.content.length>50){try{let P=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:P,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:d,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
98
|
-
|
|
99
|
-
Agent: ${l.content}`,meta:f?.path?.length?{intentPath:f.path,intentPathLabel:f.pathLabel}:void 0})}catch{}Le(e.agentId,e.message,l.content,{channel:d,chatId:g,sender:p},this.memoryStore).catch(()=>{}),ft(e.agentId,e.message,l.content,{channel:d,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let b=l.billedModel||e.model||n.def.model,S=e.context?.channel,M=S&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${S}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,l.duration||0,l.usage,e.message.length,l.content.length,!1,b,S,M),this.log(`[${e.agentId}] completed in ${l.duration}ms`+(l.tokensUsed?` (${l.tokensUsed} tokens)`:""))}return l}catch(l){return n.errors++,this.log(`[${e.agentId}] unexpected error: ${l.message}`),j={content:"",error:l.message},j}finally{n.activeTasks--;let l=n.runningTasks.findIndex(m=>m.id===c.id);l!==-1&&n.runningTasks.splice(l,1),a.done=!0,a.endedAt=new Date;for(let m of a.subscribers)try{m(`
|
|
100
|
-
[task finished]
|
|
101
|
-
`)}catch{}a.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(c.id),qn).unref?.();try{let m=a.endedAt,b={id:c.id,agentId:e.agentId,channel:c.channel,chatId:c.chatId,sender:c.sender,message:e.message||"",startedAt:c.startedAt.toISOString(),endedAt:m.toISOString(),durationMs:m.getTime()-c.startedAt.getTime(),ok:!j?.error,error:j?.error,responseText:j?.content||"",transcript:a.buffer};this.persistTaskRecord(b);let S=(b.responseText||b.error||"").trim();if(S){let M=S.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:M,at:m,ok:b.ok})}}catch(m){this.log(`[${e.agentId}] task history persist failed: ${m?.message}`)}this.messageQueue.markDone(e.agentId,s,r).then(m=>{if(m.length!==0){this.log(`[${e.agentId}] flushing ${m.length} queued message(s)`);for(let b of m)this.execute({message:b.text,agentId:e.agentId,context:b.originalContext||{channel:b.channel,sender:b.sender,chatId:b.chatId}}).catch(S=>{this.log(`[${e.agentId}] queued message failed: ${S.message}`)})}}).catch(m=>{this.log(`[${e.agentId}] queue flush failed: ${m.message}`)})}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=A(process.cwd(),z,this.safe(e.agentId),t);E(n)||Wn(n,{recursive:!0});let s=A(n,`${this.safe(e.id)}.json`);Kn(s,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),s=this.sparklineCache.get(e);if(s&&n-s.at<6e4&&s.hourly.length===t)return s.hourly;let r=new Array(t).fill(0),i=n-t*36e5,c=A(process.cwd(),z,this.safe(e));if(!E(c))return this.sparklineCache.set(e,{hourly:r,at:n}),r;let a=new Date(n).toISOString().slice(0,10),u=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let d of[u,a]){let g=A(c,d);if(E(g))try{for(let p of _(g)){if(!p.endsWith(".json"))continue;let k=p.split("-")[0],f=parseInt(k,10);if(!Number.isFinite(f)||f<i||f>n)continue;let w=Math.floor((n-f)/36e5),I=t-1-w;I>=0&&I<t&&r[I]++}}catch{}}return this.sparklineCache.set(e,{hourly:r,at:n}),r}hydrateLastSummariesFromDisk(){let e=A(process.cwd(),z);if(!E(e))return 0;let t=0;for(let n of _(e)){let s=A(e,n),r;try{r=_(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of r){let c=A(s,i),a;try{a=_(c).filter(u=>u.endsWith(".json")).sort().reverse()}catch{continue}for(let u of a)try{let h=JSON.parse(Oe(A(c,u),"utf-8")),d=(h.responseText||h.error||"").trim();if(!d)continue;let g=d.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(h.agentId,{text:g,at:new Date(h.endedAt),ok:h.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Gn){let t=A(process.cwd(),z);if(!E(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=0;for(let r of _(t)){let i=A(t,r),c;try{c=_(i)}catch{continue}for(let a of c){let u=Date.parse(a+"T00:00:00Z");if(!(Number.isNaN(u)||u>=n))try{Bn(A(i,a),{recursive:!0,force:!0}),s++}catch{}}}return s}listTaskHistory(e,t=50){let n=A(process.cwd(),z,this.safe(e));if(!E(n))return[];let s=_(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),r=[];for(let i of s){if(r.length>=t)break;let c=A(n,i),a;try{a=_(c).filter(u=>u.endsWith(".json"))}catch{continue}a.sort().reverse();for(let u of a){if(r.length>=t)break;try{let h=JSON.parse(Oe(A(c,u),"utf-8")),{transcript:d,responseText:g,...p}=h;r.push(p)}catch{}}}return r}getTaskRecord(e,t){let n=A(process.cwd(),z,this.safe(e));if(!E(n))return null;let s=this.safe(t),r=_(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of r){let c=A(n,i,`${s}.json`);if(E(c))try{return JSON.parse(Oe(c,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};export{Kt as a,Gt as b,Jt as c,Ze as d,he as e,Q as f,sr as g,rr as h,At as i};
|
|
102
|
-
//# sourceMappingURL=chunk-23AUU4S2.js.map
|