agentix-cli 0.16.0 → 0.18.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-RDVGL2TW.js +2 -0
- package/dist/audit-Z47AQFFD.js +3 -0
- package/dist/audit-Z47AQFFD.js.map +1 -0
- package/dist/board-dashboard-KX2CNOSY.js +7282 -0
- package/dist/board-dashboard-KX2CNOSY.js.map +1 -0
- package/dist/chunk-34NG7UDX.js +11 -0
- package/dist/chunk-34NG7UDX.js.map +1 -0
- package/dist/{chunk-6MKAXEE5.js → chunk-4ITQP3XL.js} +2 -2
- package/dist/{chunk-6MKAXEE5.js.map → chunk-4ITQP3XL.js.map} +1 -1
- package/dist/chunk-53NRX2NA.js +2 -0
- package/dist/chunk-53NRX2NA.js.map +1 -0
- package/dist/chunk-6PPIFDOQ.js +1742 -0
- package/dist/chunk-6PPIFDOQ.js.map +1 -0
- package/dist/chunk-AFRHKA7B.js +2 -0
- package/dist/chunk-AFRHKA7B.js.map +1 -0
- package/dist/chunk-ASSJ4Z6Z.js +164 -0
- package/dist/chunk-ASSJ4Z6Z.js.map +1 -0
- package/dist/chunk-BLUXL6HR.js +854 -0
- package/dist/chunk-BLUXL6HR.js.map +1 -0
- package/dist/chunk-BTAEYL3P.js +72 -0
- package/dist/chunk-BTAEYL3P.js.map +1 -0
- package/dist/chunk-CDNWCYF7.js +2 -0
- package/dist/chunk-CDNWCYF7.js.map +1 -0
- package/dist/chunk-DJEZ2HVU.js +5 -0
- package/dist/chunk-DJEZ2HVU.js.map +1 -0
- package/dist/{chunk-FLOGK2U7.js → chunk-DSCMCVTV.js} +3 -3
- package/dist/chunk-DSCMCVTV.js.map +1 -0
- package/dist/chunk-EW27SCCC.js +2 -0
- package/dist/chunk-EW27SCCC.js.map +1 -0
- package/dist/chunk-HPDHNIA3.js +2 -0
- package/dist/chunk-IM376SD6.js +13 -0
- package/dist/chunk-IM376SD6.js.map +1 -0
- package/dist/chunk-J4WKMKTP.js +5 -0
- package/dist/{chunk-YI2T5QYB.js.map → chunk-J4WKMKTP.js.map} +1 -1
- package/dist/chunk-JGXE2YNV.js +46 -0
- package/dist/chunk-JGXE2YNV.js.map +1 -0
- package/dist/chunk-JXEPJ3YD.js +118 -0
- package/dist/chunk-JXEPJ3YD.js.map +1 -0
- package/dist/chunk-LY7JGDV7.js +6 -0
- package/dist/chunk-LY7JGDV7.js.map +1 -0
- package/dist/chunk-N67JZAXU.js +2 -0
- package/dist/chunk-N67JZAXU.js.map +1 -0
- package/dist/chunk-SR3X25TN.js +3 -0
- package/dist/chunk-SR3X25TN.js.map +1 -0
- package/dist/{chunk-7MBTMCKY.js → chunk-TRQSP67X.js} +2 -2
- package/dist/chunk-U364GNQX.js +719 -0
- package/dist/chunk-U364GNQX.js.map +1 -0
- package/dist/chunk-VJUTQAPJ.js +2 -0
- package/dist/chunk-VJUTQAPJ.js.map +1 -0
- package/dist/{chunk-HI24KAEY.js → chunk-WJXU5F4Z.js} +3 -4
- package/dist/{chunk-HI24KAEY.js.map → chunk-WJXU5F4Z.js.map} +1 -1
- package/dist/{chunk-QZP65I2H.js → chunk-ZE2YFX4K.js} +2 -2
- package/dist/cli.js +1 -320
- package/dist/cli.js.map +1 -1
- package/dist/{compaction-JBZZ7I7Y.js → compaction-S5H6DTOR.js} +6 -6
- package/dist/compaction-S5H6DTOR.js.map +1 -0
- package/dist/config-UOHEG4BW.js +2 -0
- package/dist/config-mutator-KSEBWKJH.js +2 -0
- package/dist/context-planner-2RGHJHSO.js +17 -0
- package/dist/context-planner-2RGHJHSO.js.map +1 -0
- package/dist/debug-TGAP7E7W.js +2 -0
- package/dist/discover-OATU7SHI.js +4 -0
- package/dist/discover-OATU7SHI.js.map +1 -0
- package/dist/editor-chat-FUBQLMAQ.js +137 -0
- package/dist/editor-chat-FUBQLMAQ.js.map +1 -0
- package/dist/heal-YP7QI7D3.js +2 -0
- package/dist/inbox-O5UB3YQN.js +315 -0
- package/dist/inbox-O5UB3YQN.js.map +1 -0
- package/dist/index.d.ts +3390 -1814
- package/dist/index.js +23 -53
- package/dist/index.js.map +1 -1
- package/dist/ingest-whatsapp-C3O5UPBX.js +6 -0
- package/dist/ingest-whatsapp-C3O5UPBX.js.map +1 -0
- package/dist/loader-BGWA7IRY.js +2 -0
- package/dist/loader-LBHKSXBK.js +2 -0
- package/dist/memory-extract-KKPKAOPH.js +2 -0
- package/dist/processes-7W27G3J3.js +256 -0
- package/dist/processes-7W27G3J3.js.map +1 -0
- package/dist/program-2MDELQLX.js +2 -0
- package/dist/providers-WCQSKTNP.js +2 -0
- package/dist/query-FZAL7AQD.js +2 -0
- package/dist/recipes-LZ56TA3X.js +2 -0
- package/dist/registry-ONJSILH4.js +2 -0
- package/dist/scheduler-XRM2RJIV.js +2 -0
- package/dist/slack-D27BE37Q.js +3 -0
- package/dist/slack-D27BE37Q.js.map +1 -0
- package/dist/store-4UCO56K2.js +2 -0
- package/dist/store-4UCO56K2.js.map +1 -0
- package/dist/{subagent-2SJHSSJS.js → subagent-EPOT3QDM.js} +2 -2
- package/dist/task-store-3NUWLYRY.js +2 -0
- package/dist/task-store-3NUWLYRY.js.map +1 -0
- package/dist/telegram-UWV67KWG.js +3 -0
- package/dist/telegram-UWV67KWG.js.map +1 -0
- package/dist/timers-QB4KYNAE.js +2 -0
- package/dist/timers-QB4KYNAE.js.map +1 -0
- package/dist/types-ECMEC5BZ.js +2 -0
- package/dist/types-ECMEC5BZ.js.map +1 -0
- package/dist/types-TTB6DJUE.js +2 -0
- package/dist/types-TTB6DJUE.js.map +1 -0
- package/dist/usage-dashboard-FQGPPABD.js +803 -0
- package/dist/usage-dashboard-FQGPPABD.js.map +1 -0
- package/dist/web/workflow-editor.global.js +1450 -0
- package/dist/web/workflow-editor.global.js.map +1 -0
- package/dist/whatsapp-KJ2NRKKQ.js +3 -0
- package/dist/whatsapp-KJ2NRKKQ.js.map +1 -0
- package/dist/{whatsapp-state-6D6FHHD2.js → whatsapp-state-3ZVQ6MQD.js} +2 -2
- package/dist/{wiki-UDPYFJBL.js → wiki-OUYKM7MB.js} +2 -2
- package/dist/wiki-OUYKM7MB.js.map +1 -0
- package/dist/workspace-setup-6GDBEORT.js +2 -0
- package/dist/workspace-setup-6GDBEORT.js.map +1 -0
- package/package.json +19 -2
- package/dist/agent-BCDPSPKU.js +0 -2
- package/dist/board-dashboard-LA7WW56M.js +0 -5668
- package/dist/board-dashboard-LA7WW56M.js.map +0 -1
- package/dist/chunk-6U2XOQHU.js +0 -7
- package/dist/chunk-6U2XOQHU.js.map +0 -1
- package/dist/chunk-7FJQGD6U.js +0 -6
- package/dist/chunk-7FJQGD6U.js.map +0 -1
- package/dist/chunk-ABDP7TDL.js +0 -71
- package/dist/chunk-ABDP7TDL.js.map +0 -1
- package/dist/chunk-CXY2RYNI.js +0 -11
- package/dist/chunk-CXY2RYNI.js.map +0 -1
- package/dist/chunk-FIOB3MEX.js +0 -2
- package/dist/chunk-FLOGK2U7.js.map +0 -1
- package/dist/chunk-HVC6FJNP.js +0 -108
- package/dist/chunk-HVC6FJNP.js.map +0 -1
- package/dist/chunk-K7BE4E35.js +0 -138
- package/dist/chunk-K7BE4E35.js.map +0 -1
- package/dist/chunk-KXJSLLSQ.js +0 -199
- package/dist/chunk-KXJSLLSQ.js.map +0 -1
- package/dist/chunk-KXZMYLHQ.js +0 -46
- package/dist/chunk-KXZMYLHQ.js.map +0 -1
- package/dist/chunk-M7HKBG3V.js +0 -2
- package/dist/chunk-M7HKBG3V.js.map +0 -1
- package/dist/chunk-MCJUAE6V.js +0 -6
- package/dist/chunk-MCJUAE6V.js.map +0 -1
- package/dist/chunk-RB7265LO.js +0 -12
- package/dist/chunk-RB7265LO.js.map +0 -1
- package/dist/chunk-YI2T5QYB.js +0 -5
- package/dist/compaction-JBZZ7I7Y.js.map +0 -1
- package/dist/config-LN6JEHMF.js +0 -2
- package/dist/config-mutator-24TH7PHM.js +0 -2
- package/dist/debug-3MEUO2P2.js +0 -2
- package/dist/heal-WKY5I4KB.js +0 -2
- package/dist/loader-PTCXLJEX.js +0 -2
- package/dist/memory-extract-AD7KMRPC.js +0 -2
- package/dist/providers-VUIWO3ZK.js +0 -2
- package/dist/query-PKGYE5HR.js +0 -2
- package/dist/registry-ASC2QS5K.js +0 -2
- package/dist/scheduler-A3TQOCKT.js +0 -2
- package/dist/types-OIFU3KSQ.js +0 -2
- package/dist/usage-dashboard-QX3CF6KK.js +0 -404
- package/dist/usage-dashboard-QX3CF6KK.js.map +0 -1
- package/dist/workspace-setup-ZWTT42XT.js +0 -2
- /package/dist/{agent-BCDPSPKU.js.map → agent-RDVGL2TW.js.map} +0 -0
- /package/dist/{chunk-FIOB3MEX.js.map → chunk-HPDHNIA3.js.map} +0 -0
- /package/dist/{chunk-7MBTMCKY.js.map → chunk-TRQSP67X.js.map} +0 -0
- /package/dist/{chunk-QZP65I2H.js.map → chunk-ZE2YFX4K.js.map} +0 -0
- /package/dist/{config-LN6JEHMF.js.map → config-UOHEG4BW.js.map} +0 -0
- /package/dist/{config-mutator-24TH7PHM.js.map → config-mutator-KSEBWKJH.js.map} +0 -0
- /package/dist/{debug-3MEUO2P2.js.map → debug-TGAP7E7W.js.map} +0 -0
- /package/dist/{heal-WKY5I4KB.js.map → heal-YP7QI7D3.js.map} +0 -0
- /package/dist/{loader-PTCXLJEX.js.map → loader-BGWA7IRY.js.map} +0 -0
- /package/dist/{memory-extract-AD7KMRPC.js.map → loader-LBHKSXBK.js.map} +0 -0
- /package/dist/{providers-VUIWO3ZK.js.map → memory-extract-KKPKAOPH.js.map} +0 -0
- /package/dist/{query-PKGYE5HR.js.map → program-2MDELQLX.js.map} +0 -0
- /package/dist/{registry-ASC2QS5K.js.map → providers-WCQSKTNP.js.map} +0 -0
- /package/dist/{scheduler-A3TQOCKT.js.map → query-FZAL7AQD.js.map} +0 -0
- /package/dist/{types-OIFU3KSQ.js.map → recipes-LZ56TA3X.js.map} +0 -0
- /package/dist/{wiki-UDPYFJBL.js.map → registry-ONJSILH4.js.map} +0 -0
- /package/dist/{workspace-setup-ZWTT42XT.js.map → scheduler-XRM2RJIV.js.map} +0 -0
- /package/dist/{subagent-2SJHSSJS.js.map → subagent-EPOT3QDM.js.map} +0 -0
- /package/dist/{whatsapp-state-6D6FHHD2.js.map → whatsapp-state-3ZVQ6MQD.js.map} +0 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import{a as $e}from"./chunk-34NG7UDX.js";import{a as Ce}from"./chunk-5F3J55LG.js";import{a as Ae,b as Me,d as De}from"./chunk-WJXU5F4Z.js";import{b as ke}from"./chunk-LEIYC3BF.js";import{b as ve,c as Ie}from"./chunk-WZEYII2S.js";import{a as se,b as Re}from"./chunk-SR3X25TN.js";import{a as re,b as Pe}from"./chunk-53NRX2NA.js";import{a as Te}from"./chunk-TRQSP67X.js";import{c as q,d as K}from"./chunk-QOYAX2FT.js";import{execa as ft}from"execa";import{execFile as yt}from"child_process";function N(r){let e=(r||"").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,i=typeof s?.type=="string"?s.type:void 0,o=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 o&&/out of extra usage/i.test(o)?{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}:o&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit/i.test(o)?{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}:o&&/context|prompt is too long|too many tokens|maximum context length/i.test(o)?{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}:i==="authentication_error"||o&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(o)?{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}:i==="permission_error"||a===403?{kind:"permission",retryable:!1,message:o||"The API key doesn't have permission for this request.",raw:e}:i==="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}:i==="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}:i==="invalid_request_error"||a===400?{kind:"invalid_request",retryable:!1,message:o||"The model rejected the request as invalid.",raw:e}:a&&a>=500?{kind:"upstream_api",retryable:!0,message:o||`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 H(r){return r.fix?`${r.message} \u2014 ${r.fix}`:r.message}function ie(r,e,t){let n=[];if(e.context&&!t){let s=e.context,i=["","[Environment]"],o=s.channel==="gitlab"||s.channel?.startsWith("webhook:"),c=s.channel==="telegram";if(s.channel&&i.push(`Channel: ${s.channel}`),s.group&&i.push(`Group: ${s.group}`),s.sender&&i.push(`Message from: ${s.sender}`),s.myHandle&&i.push(`Your handle on this channel: ${s.myHandle}`),o&&(i.push(""),i.push("[IMPORTANT: You are responding to a GitLab comment/event]"),i.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),i.push("- Lead with the result or action, not a narration of what you plan to do"),i.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),i.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),i.push("- Do NOT try to delegate to other agents \u2014 reply directly"),i.push("- Reference issues with #IID and MRs with !IID")),c&&s.peers?.length){i.push(""),i.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let a of s.peers){let l=a.handle?` (mention: ${a.handle})`:"",m=a.role?` \u2014 ${a.role}`:"";i.push(`\u2022 ${a.name}${l}${m}`)}i.push(""),i.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(i.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 _e(r,e,t,n,s,i){let o=["-p",e,"--output-format",t?"stream-json":"json"];t&&o.push("--verbose"),n&&o.push("--resume",n);let c=s||r.model;return c&&o.push("--model",c),r.permissionMode==="bypassPermissions"&&o.push("--dangerously-skip-permissions"),i&&i.trim().length>0&&o.push("--append-system-prompt",i),o}function bt(r){try{let e=JSON.parse(r);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 xt(r){try{let e=JSON.parse(r),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:r}}}async function wt(r,e,t,n){let s=Date.now(),i=ie(r,e,t),o=_e(r,i,!1,n,e.model,e.systemPromptAppend);try{let c=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),{stdout:a,stderr:l,exitCode:m}=await new Promise((f,S)=>{yt("claude",o,{cwd:r.workspace,timeout:c,maxBuffer:10485760,env:{...process.env,HOME:process.env.HOME||"/home/"+(process.env.USER||"user")}},(v,T,M)=>{f({stdout:T||"",stderr:M||"",exitCode:v?v.code??1:0})}).stdin?.end()});if(!a&&m!==0){let f;return m===143?f=`Claude Code timed out after ${Math.round(c/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:f=l?.trim()||`Claude Code exited with code ${m}`,{content:"",error:H(N(f)),duration:Date.now()-s}}let g=bt(a);if(g)return{content:"",error:H(N(g)),duration:Date.now()-s};let h=xt(a);return{content:h.text,duration:Date.now()-s,claudeSessionId:h.sessionId,usage:h.usage,billedModel:h.billedModel}}catch(c){return console.error(`[runtime] execFile threw: ${c.message}`),{content:"",error:c.message||"Claude Code failed",duration:Date.now()-s}}}async function St(r,e,t,n,s,i){let o=Date.now(),c=ie(r,e,n),a=_e(r,c,!0,s,e.model,e.systemPromptAppend),l="",m,g,h,f;try{let S=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),x=ft("claude",a,{cwd:r.workspace,timeout:S,reject:!1,env:process.env,buffer:!1,stdin:"ignore"});if(x.stdout){let T="";x.stdout.on("data",M=>{T+=M.toString();let D=T.split(`
|
|
4
|
+
`);T=D.pop()||"";for(let I of D)if(I.trim())try{let p=JSON.parse(I);if(i)try{i(p)}catch{}if(p.type==="assistant"&&p.message?.content){for(let w of p.message.content)if(w.type==="text"&&w.text){let k=w.text.slice(l.length);k&&(l=w.text,t(k,l))}}if(p.type==="content_block_delta"&&p.delta?.text&&(l+=p.delta.text,t(p.delta.text,l)),p.type==="result"&&p.result){if(p.is_error&&typeof p.result=="string")f=p.result;else{let w=(typeof p.result=="string",p.result);if(typeof w=="string"&&w.length>l.length){let k=w.slice(l.length);l=w,k&&t(k,l)}}p.usage&&(g={inputTokens:p.usage.input_tokens||0,outputTokens:p.usage.output_tokens||0,cacheReadTokens:p.usage.cache_read_input_tokens||0,cacheCreateTokens:p.usage.cache_creation_input_tokens||0}),typeof p.model=="string"&&(m=p.model),typeof p.session_id=="string"&&(h=p.session_id)}p.type==="system"&&p.subtype==="init"&&typeof p.model=="string"&&(m=p.model)}catch{I.trim()&&!I.startsWith("{")&&(l+=I+`
|
|
5
|
+
`,t(I+`
|
|
6
|
+
`,l))}})}let v=await x;if(!l&&v.stdout&&(l=typeof v.stdout=="string"?v.stdout:""),v.exitCode!==0&&!l){let T=typeof v.stderr=="string"?v.stderr:"",M=v,D;return M.timedOut?D=`Claude Code timed out after ${Math.round(S/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:M.signal?D=T.trim()||`Claude Code killed by signal ${M.signal}`:D=T.trim()||`Claude Code exited with code ${M.exitCode??"unknown"}`,{content:"",error:H(N(D)),duration:Date.now()-o}}return f?{content:"",error:H(N(f)),duration:Date.now()-o,usage:g,billedModel:m,claudeSessionId:h}:{content:l,duration:Date.now()-o,usage:g,billedModel:m,claudeSessionId:h}}catch(S){return{content:l||"",error:H(N(S.message)),duration:Date.now()-o,usage:g,billedModel:m,claudeSessionId:h}}}async function Tt(r,e,t,n){let s=Date.now();try{let i=await import("@anthropic-ai/claude-agent-sdk"),{query:o}=i,c=ie(r,e,n),a="",l=o({prompt:c,options:{model:e.model||r.model,cwd:r.workspace,permissionMode:"bypassPermissions"}});for await(let m of l)m.type==="result"&&m.subtype==="success"&&(a=m.result||"");return{content:a,duration:Date.now()-s}}catch(i){return{content:"",error:`SDK error: ${i.message}`,duration:Date.now()-s}}}async function vt(r,e,t,n){let s=Date.now();try{let{generate:i}=await import("./agent-RDVGL2TW.js"),o=r.provider||"claude-code",c=n?`${n}
|
|
7
|
+
|
|
8
|
+
${e.message}`:e.message,a=await i({task:c,cwd:r.workspace,provider:o,model:e.model||r.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1});return{content:a.content||"Done.",tokensUsed:a.tokensUsed,duration:Date.now()-s}}catch(i){return{content:"",error:`Orchestrator error: ${i.message}`,duration:Date.now()-s}}}async function Oe(r,e,t,n,s,i,o){switch(r.tier){case"claude-code":return n?St(r,e,n,s,i,o):wt(r,e,s,i);case"sdk":{let c=r.provider||"claude",a=t[c]?.apiKey;return a?Tt(r,e,a,s):{content:"",error:`No API key for provider "${c}". Configure providers.${c}.apiKey`}}case"orchestrator":{let c=r.provider||"claude-code",a=t[c]?.apiKey;return vt(r,e,a,s)}default:return{content:"",error:`Unknown tier: ${r.tier}`}}}import{readFileSync as oe,writeFileSync as It,mkdirSync as kt,existsSync as Ee,readdirSync as Ne}from"fs";import{resolve as G}from"path";var $t=12e3,He=30,Ct=45,At=15,Mt=18e4,Dt="[Compacted conversation summary",Rt=[/\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 Pt(r){return r?Rt.some(e=>e.test(r)):!1}var _t=[{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 je(r){if(!r)return null;let e=0;for(let t of _t)t.re.test(r)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Le(r,e,t,n){if(r.length===0)return!1;let s=r[r.length-1];return s.role===e&&(s.name??"")===t&&s.content===n}function Ot(r){let e=r.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 Q=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;constructor(e=process.cwd(),t={}){this.sessionsDir=G(e,".agentx/sessions"),Ee(this.sessionsDir)||kt(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Ct),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??At),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Mt)}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 G(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 i=this.sessionFile(s);if(Ee(i))try{let a=JSON.parse(oe(i,"utf-8"));return this.cache.set(s,a),a}catch{}let o=new Date().toISOString().slice(0,10),c={id:s,agentId:e,channel:t,chatId:n,day:o,messages:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return this.cache.set(s,c),this.save(c),c}addUserMessage(e,t,n,s,i){let o=this.getSession(e,t,n);Le(o.messages,"user",s,i)||(o.messages.push({role:"user",name:s,content:i,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}addAgentMessage(e,t,n,s){let i=this.getSession(e,t,n);Le(i.messages,"agent",e,s)||(i.messages.push({role:"agent",name:e,content:s,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,s){let i=this.getSession(e,t,n);i.claudeSessionId=s,i.updatedAt=new Date().toISOString(),this.save(i)}buildHistoryContext(e,t,n){let s=this.getSession(e,t,n);if(s.messages.length===0)return"";let i=[`[Conversation history for today (${s.day})]`],o="";for(let c of s.messages){let a=Ot(c.timestamp);a!==o&&(i.push(`\u2014 ${a} \u2014`),o=a);let l=c.name||(c.role==="user"?"User":"Agent");i.push(`${l}: ${c.content}`)}return i.push("[End of history \u2014 respond to the latest message above]"),i.push(""),i.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(),i=e.after??s,o=e.before??new Date(Date.now()+1e3).toISOString(),c=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),a;try{a=Ne(this.sessionsDir).filter(I=>I.startsWith(`${c}:`)&&I.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let l=i.slice(0,10),m=o.slice(0,10),g=/:(\d{4}-\d{2}-\d{2})\.json$/,h=a.filter(I=>{let p=I.match(g);if(!p)return!1;let w=p[1];return w>=l&&w<=m}),f=[],S=0,x=e.query?.toLowerCase(),v=e.participants?.length?new Set(e.participants):void 0;for(let I of h){let p;try{p=JSON.parse(oe(G(this.sessionsDir,I),"utf-8"))}catch{continue}if(p.agentId===e.agentId&&!(e.channel&&p.channel!==e.channel)&&!(e.chatId&&p.chatId!==e.chatId))for(let w of p.messages)S++,!(!w.timestamp||w.timestamp<i||w.timestamp>=o)&&(v&&w.role==="user"&&!v.has(w.name??"")||x&&!w.content.toLowerCase().includes(x)||f.push({ts:w.timestamp,role:w.role,senderName:w.name??"",content:w.content,channel:p.channel,chatId:p.chatId,day:p.day,sessionFile:I}))}f.sort((I,p)=>p.ts.localeCompare(I.ts));let T=f.slice(0,t),M=T.length>0?T[T.length-1].ts:null,D=f.length>t;return{turns:T,oldestTs:M,hasMore:D,totalScanned:S}}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!==""&&!Pt(s))return"";let i=new Date().toISOString().slice(0,10),o=this.sessionKey(e,t,n);try{let c=Ne(this.sessionsDir).filter(l=>l.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&l.includes(i)&&l.endsWith(".json")),a=[];for(let l of c)try{let m=JSON.parse(oe(G(this.sessionsDir,l),"utf-8"));if(m.id===o||m.messages.length===0)continue;let g=m.messages.slice(-4),f=!m.chatId.startsWith("-")&&/^\d+$/.test(m.chatId)?"DM":m.chatId,S=g.map(x=>` [${x.timestamp.slice(11,16)}] ${x.name||x.role}: ${x.content.slice(0,200)}`);a.push(`From ${f} (${m.channel}):
|
|
10
|
+
${S.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 i=this.getSession(e,t,n),{needsCompaction:o,compactSession:c,applyCompaction:a}=await import("./compaction-S5H6DTOR.js");if(!o(i.messages))return{compacted:!1};let l=await c(i.messages,e,s);return l.compactedCount===0?{compacted:!1}:(i.messages=a(i.messages,l),i.updatedAt=new Date().toISOString(),this.save(i),{compacted:!0,qualityScore:l.qualityScore,lostEntities:l.lostEntities,drift:l.drift})}hasCompaction(e,t,n){let s=this.getSession(e,t,n);return s.messages.length>0&&s.messages[0].content.startsWith(Dt)}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 i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(s.inputTokens||0)+(s.cacheReadTokens||0)+(s.cacheCreateTokens||0),i.updatedAt=new Date().toISOString(),this.save(i)}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){e.messages.length>He&&(e.messages=e.messages.slice(-He));let t=e.messages.reduce((n,s)=>n+s.content.length,0);for(;t>$t&&e.messages.length>2;){let n=e.messages.shift();t-=n.content.length}}save(e){try{let t=this.sessionFile(e.id);It(t,JSON.stringify(e,null,2))}catch{}}};var J=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,i=n.filter(a=>a>s),o=t-6e4,c=i.filter(a=>a>o);if(c.length>=this.maxPerMinute){let a=c[0],l=Math.max(50,a+6e4-t);return{allowed:!1,reason:`Rate limit: ${c.length}/${this.maxPerMinute} per minute`,waitMs:l}}if(i.length>=this.maxPerHour){let a=i[0],l=Math.max(1e3,a+36e5-t);return{allowed:!1,reason:`Rate limit: ${i.length}/${this.maxPerHour} per hour`,waitMs:l}}return i.push(t),this.windows.set(e,i),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,s=Date.now()+n,i=!0;for(;;){let o=this.check(e);if(o.allowed)return{ok:!0};if(Date.now()>=s)return{ok:!1,reason:`${o.reason} (waited ${Math.round(n/1e3)}s, giving up)`};i&&(i=!1,t.onWait?.(o.reason,o.waitMs));let c=s-Date.now(),a=Math.min(o.waitMs??1e3,c,5e3);await new Promise(l=>setTimeout(l,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}}};var Et={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}},Fe=4;function Ue(r,e=Et){let t=Nt(r,e);t.sort((o,c)=>o.priority-c.priority);let n=[],s=0,i=e.totalBudget*Fe;for(let o of t){if(!o.content)continue;let c=o.maxTokens*Fe,a=o.content.length>c?o.content.slice(0,c)+"...":o.content;if(s+a.length>i){let l=i-s;l>100&&n.push(a.slice(0,l)+"...");break}n.push(a),s+=a.length}return n.join(`
|
|
13
|
+
|
|
14
|
+
`)}function Nt(r,e){let t=(o,c)=>e.layerBudgets?.[o]??c,n=[];if(n.push(Ht(r,t("channel",200))),n.push(Lt(r,t("scope",200))),r.landscape&&n.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:r.landscape,tags:["landscape","world-model"]}),r.systemPrompt&&n.push({name:"identity",priority:4,maxTokens:t("identity",200),content:r.systemPrompt.split(`
|
|
15
|
+
`)[0],tags:["identity",r.agentId]}),r.bootstrapContext&&n.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:r.bootstrapContext,tags:["bootstrap","identity","personality"]}),r.references&&n.push({name:"references",priority:4.7,maxTokens:t("references",500),content:r.references,tags:["references","verified","deterministic"]}),r.intent&&r.intent.path.length>0){let o=[`[Intent path: ${r.intent.pathLabel}${r.intent.status==="pending"?" (pending approval)":""}]`],c=r.intent.path[r.intent.path.length-1],a=r.intent.axes?.[c];if(a&&Object.keys(a).length){let l=Object.entries(a).map(([m,g])=>` ${m}: ${g}`).join(`
|
|
16
|
+
`);o.push(l)}r.intent.leaf?.input&&o.push(` input: ${r.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:o.join(`
|
|
17
|
+
`),tags:["intent",...r.intent.path]})}else{let o=jt(r.message);o.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${o.join(", ")}]`,tags:o})}let s=[];r.replyToText&&s.push(`[Replying to]: ${r.replyToText.slice(0,300)}`),r.mediaPath&&(s.push(`[Attached file: ${r.mediaPath}]`),s.push(`[File type: ${r.mediaType||"unknown"}]`),r.mediaType?.startsWith("image/")?s.push("Please view this image and respond to it."):r.mediaType?.startsWith("audio/")&&s.push("Please transcribe this audio and respond.")),r.issueMR&&s.push(`[${r.issueMR.type} #${r.issueMR.iid}: ${r.issueMR.title}]`),s.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:s.join(`
|
|
18
|
+
`),tags:["artifacts",...r.mediaType?["media"]:[]]}),r.skillInjection&&n.push({name:"skills",priority:6.2,maxTokens:t("skills",2e3),content:r.skillInjection,tags:["skills","auto-inject"]}),r.patternContext&&n.push({name:"patterns",priority:6.3,maxTokens:t("patterns",400),content:r.patternContext,tags:["patterns","behavioral","self-improving"]}),r.memoryContext&&n.push({name:"memory",priority:6.5,maxTokens:t("memory",600),content:r.memoryContext,tags:["memory","persistent"]});let i=r.groupHistory||r.sessionHistory;if(i&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:i,tags:["history","conversation"]}),r.crossChatContext&&n.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:r.crossChatContext,tags:["history","cross-chat"]}),r.longMemoryRecall&&n.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:r.longMemoryRecall,tags:["history","long-memory"]}),r.handoverNote){let o=[`[Handover] You are taking over this conversation from ${r.handoverNote.fromAgent}.`];r.handoverNote.summary&&o.push(`Operator summary: ${r.handoverNote.summary}`),o.push(`Handover time: ${r.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:o.join(`
|
|
19
|
+
`),tags:["handover",r.handoverNote.fromAgent]})}return r.wikiContext&&n.push({name:"wiki",priority:8,maxTokens:t("wiki",1e3),content:r.wikiContext,tags:["wiki","knowledge"]}),n}function Ht(r,e){let t=[`Channel: ${r.channel}`];r.chatId&&t.push(`Chat ID: ${r.chatId} (use this verbatim in /recall, /send)`);let n=[],s=[r.channel];switch(r.channel){case"telegram":r.agentHandle&&t.push(`Your handle: ${r.agentHandle}`),t.push(`From: ${r.sender}`),r.senderId&&t.push(`Telegram user ID: ${r.senderId}`),r.senderUsername&&t.push(`Username: @${r.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: ${r.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: ${r.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: ${r.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:r.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(i=>`- ${i}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
20
|
+
`),tags:s,rules:n}}function Lt(r,e){let t=[],n=[];if(r.channelScope==="group"&&r.groupName?(t.push(`Group: ${r.groupName}`),n.push("group",r.groupName)):r.channelScope==="project"&&r.projectPath?(t.push(`Project: ${r.projectPath}`),n.push("project",r.projectPath)):r.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),r.channelMeta){let s=r.channelMeta;if(s.agents?.length&&(t.push(`[Verified bots in this chat: ${s.agents.map(i=>i.handle||i.name||i.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 i of s.facts)t.push(`\u2022 ${i}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
21
|
+
`),tags:n}}function jt(r){let e=[],t=r.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 Ft,writeFileSync as Be,appendFileSync as Ut,mkdirSync as Bt,existsSync as We}from"fs";import{resolve as ae}from"path";var qe=200,Wt=7,z=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=ae(e,".agentx/memory"),We(this.memoryDir)||Bt(this.memoryDir,{recursive:!0})}filePath(e){return ae(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()};Ut(this.filePath(e),JSON.stringify(n)+`
|
|
22
|
+
`)}getAll(e){let t=this.filePath(e);if(!We(t))return[];try{return Ft(t,"utf-8").split(`
|
|
23
|
+
`).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 i=s.map(f=>`${f.keywords.join(" ")} ${f.content}`),o=ae(this.memoryDir,`${t}_bm25_cache.json`),c=K(i,o),a=q(e,c),l=new Map(a.map(f=>[f.docIndex,f.score])),g=s.map((f,S)=>{let x=l.get(S)??0;return f.category==="secret"&&(x+=2),f.category==="commitment"&&(x+=1),{memory:f,score:x}}).filter(f=>f.score>0);if(g.length===0)return s.slice(-n);let h=g.sort((f,S)=>S.score-f.score).slice(0,n).map(f=>f.memory);if(h.length>0)try{this.recordAccess(t,h.map(f=>f.id))}catch{}return h}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 o=!s.source.chatId.startsWith("-")&&/^\d+$/.test(s.source.chatId)?"DM":s.source.chatId,c=`- [${s.category}] ${s.content} (${o}, ${s.source.date})`;if(n+c.length>2400)break;t.push(c),n+=c.length}return t.push("[End Memory]"),t.join(`
|
|
24
|
+
`)}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),s=new Set(t),i=!1;for(let o of n)if(s.has(o.id)){o.accessCount=(o.accessCount||0)+1,o.lastAccessed=new Date().toISOString();let c=o.intervalDays||1;o.intervalDays=Math.min(c*2,30),o.nextReview=new Date(Date.now()+o.intervalDays*864e5).toISOString(),i=!0}i&&Be(this.filePath(e),n.map(o=>JSON.stringify(o)).join(`
|
|
25
|
+
`)+`
|
|
26
|
+
`)}getDueForReview(e,t=5){let n=this.getAll(e),s=Date.now();return n.filter(i=>i.category==="task-state"?!1:i.nextReview?new Date(i.nextReview).getTime()<=s:!0).sort((i,o)=>!i.nextReview&&o.nextReview?-1:i.nextReview&&!o.nextReview?1:i.nextReview&&o.nextReview?new Date(i.nextReview).getTime()-new Date(o.nextReview).getTime():(i.accessCount||0)-(o.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 i=Math.round((Date.now()-new Date(s.createdAt).getTime())/864e5);n.push(`- [${s.category}] ${s.content} (${i}d old, accessed ${s.accessCount||0}x)`)}return n.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),n.join(`
|
|
27
|
+
`)}hasSimilar(e,t){let n=this.getAll(e),i=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let c=o.content.toLowerCase();return i.filter(l=>c.includes(l)).length>=i.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let n=Date.now(),s=Wt*24*60*60*1e3;t=t.filter(o=>o.category==="task-state"&&o.expiresAt?new Date(o.expiresAt).getTime()>n:o.category==="task-state"&&!o.expiresAt?n-new Date(o.createdAt).getTime()<s:!0),t.length>qe&&(t=t.slice(-qe));let i=this.filePath(e);Be(i,t.map(o=>JSON.stringify(o)).join(`
|
|
28
|
+
`)+`
|
|
29
|
+
`)}};var X=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 i=this.getOrCreate(e,t,n);if(!i.running)return null;switch(i.mode){case"drop":return"drop";case"collect":case"followup":return i.pending.push(s),i.mode}}async markDone(e,t,n){let s=this.getOrCreate(e,t,n);if(s.running=!1,s.pending.length===0)return[];let i=[...s.pending];switch(s.pending=[],s.mode){case"collect":{let o={text:i.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
|
|
30
|
+
`),sender:i[i.length-1].sender,timestamp:Date.now(),channel:i[0].channel,chatId:i[0].chatId,originalContext:i[i.length-1].originalContext};return s.onFlush&&await s.onFlush([o]),[o]}case"followup":return s.onFlush&&await s.onFlush(i),i;case"drop":return[];default:return i}}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 qt,writeFileSync as Ke,appendFileSync as Kt,mkdirSync as Gt,existsSync as Ge}from"fs";import{resolve as ce}from"path";var Qe=50,Qt="claude-haiku-4-20250514",Jt=`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.
|
|
31
|
+
|
|
32
|
+
Extract patterns like:
|
|
33
|
+
- "When asked about X, the approach that works is Y"
|
|
34
|
+
- "User prefers Z style of communication"
|
|
35
|
+
- "For deployment tasks, always check A before doing B"
|
|
36
|
+
- "This codebase uses pattern X, so generate code following X"
|
|
37
|
+
|
|
38
|
+
SKIP:
|
|
39
|
+
- Factual information (names, dates, URLs)
|
|
40
|
+
- Routine task completions
|
|
41
|
+
- Greetings or small talk
|
|
42
|
+
|
|
43
|
+
Output a JSON array:
|
|
44
|
+
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
45
|
+
|
|
46
|
+
If nothing worth extracting, output: []`,Y=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=ce(e,".agentx/patterns"),Ge(this.patternsDir)||Gt(this.patternsDir,{recursive:!0})}filePath(e){return ce(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!Ge(t))return[];try{return qt(t,"utf-8").split(`
|
|
47
|
+
`).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()};Kt(this.filePath(e),JSON.stringify(n)+`
|
|
48
|
+
`)}findRelevant(e,t,n=5){let s=this.getAll(t);if(s.length===0)return[];let i=s.map(m=>`${m.context} ${m.pattern}`),o=ce(this.patternsDir,`${t}_bm25_cache.json`),c=K(i,o),l=q(e,c).slice(0,n).map(m=>s[m.docIndex]).filter(m=>m.confidence>=.3);return l.length>0&&this.recordAccess(t,l.map(m=>m.id)),l}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(`
|
|
49
|
+
`)}hasSimilar(e,t){let n=this.getAll(e),s=t.toLowerCase().split(/\s+/).filter(i=>i.length>3);return n.some(i=>{let o=i.pattern.toLowerCase();return s.filter(a=>o.includes(a)).length>=s.length*.6})}recordAccess(e,t){let n=this.getAll(e),s=new Set(t),i=!1;for(let o of n)s.has(o.id)&&(o.accessCount++,o.lastUsed=new Date().toISOString(),o.confidence=Math.min(1,o.confidence+.05),i=!0);i&&Ke(this.filePath(e),n.map(o=>JSON.stringify(o)).join(`
|
|
50
|
+
`)+`
|
|
51
|
+
`)}prune(e){let t=this.getAll(e);t.length<=Qe||(t.sort((n,s)=>s.confidence*s.accessCount-n.confidence*n.accessCount),t=t.slice(0,Qe),Ke(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
52
|
+
`)+`
|
|
53
|
+
`))}};async function Je(r,e,t,n,s){if(e.length<30&&t.length<100)return;let{createProvider:i}=await import("./providers-WCQSKTNP.js"),a=(await i("claude").generate([{role:"system",content:Jt},{role:"user",content:`User: ${e.slice(0,500)}
|
|
54
|
+
|
|
55
|
+
Agent: ${t.slice(0,1e3)}`}],{model:Qt,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!a)return;let l=JSON.parse(a[0]);if(!(!Array.isArray(l)||l.length===0)){for(let m of l)s.hasSimilar(r,m.pattern)||s.addPattern(r,{agentId:r,pattern:m.pattern,context:m.context,confidence:m.confidence||.5,source:n});Math.random()<.05&&s.prune(r)}}import{EventEmitter as zt}from"events";var le=class{inner=new zt;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}},ue;function L(){return ue||(ue=new le),ue}import{readFileSync as Xt}from"fs";import{homedir as Yt}from"os";import{join as Zt}from"path";var F=null,Vt=6e4;function en(){try{let r=Zt(Yt(),".claude.json"),e=Xt(r,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function tn(r,e=Date.now()){if(!r)return{available:!0,checkedAt:e,unknown:!0};let t=typeof r.cachedExtraUsageDisabledReason=="string"?r.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function nn(r=!1){let e=Date.now();return!r&&F&&e-F.checkedAt<Vt||(F=tn(en(),e)),F}function ze(r){let e=nn();return e.available||r?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 Xe={warnRatio:.8},A={...Xe},sn=5*60*60*1e3,rn=60*60*1e3,E=[];function Ye(r){A={...Xe,...r||{}}}function Ze(r){let e=r-sn,t=0;for(;t<E.length&&E[t]<e;)t++;t>0&&E.splice(0,t)}function Ve(r=Date.now()){Ze(r),E.push(r)}function et(r=Date.now()){Ze(r);let e=r-rn,t=0;for(let i=E.length-1;i>=0&&E[i]>=e;i--)t++;let n=E.length,s={lastHour:t,last5h:n,maxPerHour:A.maxPerHour,maxPer5h:A.maxPer5h};return A.maxPerHour&&A.maxPerHour>0&&(s.hourlyRatio=t/A.maxPerHour),A.maxPer5h&&A.maxPer5h>0&&(s.fiveHourRatio=n/A.maxPer5h),s}function tt(r,e=Date.now()){let t=et(e);return r?null:A.maxPerHour&&t.lastHour>=A.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${A.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}:A.maxPer5h&&t.last5h>=A.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${A.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 nt(r=Date.now()){let e=et(r),t=A.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 de=new Map;function st(r,e,t){return t?`${r}:${e}:${t}`:`${r}:${e}`}function rt(r,e,t,n=Date.now()){let s=de.get(r);s||(s={key:r,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},de.set(r,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:r,timestamp:n,total:e,parts:t}),s.ring.length>100&&s.ring.shift()}function it(r){let e=de.get(r);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 ${r}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as _,mkdirSync as on,readdirSync as P,readFileSync as ge,rmSync as an,writeFileSync as cn}from"fs";import{resolve as $}from"path";var ct;function us(r){ct=r}function ls(){return ct}var ot=64*1024,un=5*60*1e3,j=".agentx/task-history",ln=30;function he(r,e=800){return r.length<=e?r:r.slice(0,e)+` \u2026[+${r.length-e} chars]`}function dn(r,e){let t=0;try{t=r.listArticles(e).length}catch{return""}if(t===0)return"";let n=$(r.baseDir,"_index.md");if(!_(n))return"";let s=process.argv[1]||"dist/cli.js",i=r.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 ${i} --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(`
|
|
56
|
+
`)}function gn(){let r="";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}
|
|
57
|
+
`}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>r.length&&(n+=s.text.slice(r.length),r=s.text);else if(s.type==="thinking"&&typeof s.thinking=="string")n+=`
|
|
58
|
+
\u{1F4AD} ${he(s.thinking,600)}
|
|
59
|
+
`;else if(s.type==="tool_use"){let i=s.name||"tool",o=s.input?he(JSON.stringify(s.input),400):"";n+=`
|
|
60
|
+
\u2192 ${i}(${o})
|
|
61
|
+
`}return n}if(t==="user"&&e.message?.content){let n="";for(let s of e.message.content)if(s.type==="tool_result"){let i=Array.isArray(s.content)?s.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof s.content=="string"?s.content:"",o=s.is_error?"\u2190 [error] ":"\u2190 ";n+=`${o}${he(i,800)}
|
|
62
|
+
`}return n}return t==="result"?`\xB7 done${e.duration_ms?` (${Math.round(e.duration_ms/1e3)}s)`:""}
|
|
63
|
+
`:""}}var at=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;messageQueue;classifier;graphStore;handoverStore=new Ce;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 Q(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new ke(void 0,void 0,"unified"),this.memoryStore=new z,this.patternStore=new Y,this.rateLimiter=new J,this.tokenTracker=new $e,this.messageQueue=new X,Ye({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new ve({baseDir:$(process.cwd(),e.graph.baseDir),log:(...s)=>t("[graph]",...s)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Ie({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,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 i=this.handoverStore.consumeSummary(t,n);if(!(!i&&s.summaryConsumedAt))return{fromAgent:s.fromAgent,summary:i||s.summary,at:s.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),s,i=0;for(let[o,c]of this.agents)for(let a of c.def.mentions){if(t.atMentionsOnly&&!a.startsWith("@"))continue;let l=a.toLowerCase();n.includes(l)&&l.length>i&&(s=o,i=l.length)}return s}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[s,i]of this.agents)for(let o of i.def.mentions)if(t.includes(o.toLowerCase())){n.push(s);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}buildPeerList(e,t){let n=[];for(let[s,i]of this.agents)s!==e&&n.push({name:i.def.name,handle:this.getChannelHandle(s,t),role:i.def.systemPrompt?.split(`
|
|
64
|
+
`)[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=this.agents.get(e.agentId);if(!n){if(this.meshFallback){let u=this.meshFallback.directory().find(d=>d.healthy&&d.skills.some(y=>y.id===e.agentId));if(u){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${u.peer}"`);try{let d=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(u.peer,e.message,e.agentId,{timeoutMs:d}),viaMesh:u.peer}}catch(d){return this.log(`[${e.agentId}] mesh fallback to "${u.peer}" failed: ${d?.message??d}`),{content:"",error:`mesh fallback failed: ${d?.message??d}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let s=e.context?.channel||"api",i=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(n.activeTasks>=n.def.maxConcurrent)if(s==="api"){let u=Date.now(),d=25*6e4,y=500;for(;n.activeTasks>=n.def.maxConcurrent;){if(Date.now()-u>d)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(d/6e4)}m`};await new Promise(b=>setTimeout(b,y))}}else{let u=n.def.queueMode||"collect",d=this.messageQueue.enqueue(e.agentId,s,i,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:s,chatId:i,originalContext:e.context});if(d==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(d){let y=this.messageQueue.pendingCount(e.agentId,s,i);return this.log(`[${e.agentId}] busy, message queued (mode: ${d}, pending: ${y})`),{content:"",error:`__queued__:${d}:${y}`}}}let o=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(u,d)=>{this.log(`[${e.agentId}] ${u} \u2014 queued, resumes in ~${Math.max(1,Math.round(d/1e3))}s`)}});if(!o.ok)return this.log(`[${e.agentId}] ${o.reason}`),{content:"",error:o.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 l=u=>{if(u){a.buffer+=u,a.buffer.length>ot&&(a.buffer=a.buffer.slice(a.buffer.length-ot));for(let d of a.subscribers)try{d(u)}catch{}}},m;if(t){let u=gn();m=d=>{let y=u(d);y&&l(y)}}this.messageQueue.markRunning(e.agentId,s,i),this.log(`[${e.agentId}] executing task (${n.activeTasks}/${n.def.maxConcurrent})`);let g=e.context?.channel||"api",h=e.context?.chatId||e.context?.group||e.context?.sender||"default",f=e.context?.sender||"User";this.sessions.addUserMessage(e.agentId,g,h,f,e.message);let S=Date.now();L().emit("task:started",{agentId:e.agentId,channel:g,chatId:h,messagePreview:(e.message||"").slice(0,200),at:new Date(S).toISOString()});let x;if(this.classifier&&g!=="a2a")try{x=await this.classifier.classify({text:e.message,channel:g,sender:e.context?.sender,agentId:e.agentId})||void 0}catch(u){this.log(`[classifier] classify failed for ${e.agentId}: ${u?.message||u}`)}let v=this.wikiHub.getAgentWiki(e.agentId),T=dn(v,e.agentId),M=this.memoryStore.findRelevant(e.message,e.agentId,8),D=this.memoryStore.buildContext(M),I=this.patternStore.findRelevant(e.message,e.agentId,5),p=this.patternStore.buildContext(I),w="";try{let{loadLocalSkills:u,getAutoInjectSkills:d}=await import("./loader-LBHKSXBK.js"),y=await u(n.def.workspace);w=d(y,e.message)}catch{}let k=n.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,g,h):void 0;if(k&&this.sessions.isSessionStale(e.agentId,g,h)&&(this.log(`[${e.agentId}] session stale for ${g}:${h}, starting fresh`),this.sessions.clearClaudeSessionId(e.agentId,g,h),L().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:h,reason:"stale",at:new Date().toISOString()}),k=void 0),k&&this.sessions.shouldRotateByTierTwo(e.agentId,g,h)){let u=this.sessions.getLastTurnInputTokens(e.agentId,g,h);this.log(`[${e.agentId}] tier-2 rotation for ${g}:${h} (last turn: ${u} input tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),this.sessions.clearClaudeSessionId(e.agentId,g,h),L().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:h,reason:"tier-2",lastTurnInputTokens:u,at:new Date().toISOString()}),k=void 0}if(k&&this.sessions.shouldRotateByTurns(e.agentId,g,h)){let u=this.sessions.getTurnCount(e.agentId,g,h);this.log(`[${e.agentId}] max-turns rotation for ${g}:${h} (${u} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),this.sessions.clearClaudeSessionId(e.agentId,g,h),L().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:h,reason:"max-turns",at:new Date().toISOString()}),k=void 0}try{let u=await this.sessions.compactIfNeeded(e.agentId,g,h,this.memoryStore);if(u.compacted){let d=u.qualityScore??"?",y=u.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${g}:${h} (quality: ${d}%, ${y} entities lost)`),u.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${u.lostEntities.slice(0,5).join(", ")}`),u.drift){let b=u.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${b.overallScore} (lexicon=${b.lexiconDecay}, tools=${b.toolShift}, semantic=${b.semanticDrift})`),b.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${b.lostWords.slice(0,5).join(", ")}`)}}}catch(u){this.log(`[${e.agentId}] compaction failed (non-fatal): ${u.message}`)}let ut=k?void 0:this.sessions.buildHistoryContext(e.agentId,g,h),me;if(n.def.contextReferences&&!k)try{let u=n.def.workspace,d=this.referencesCache.get(u);if(!d){let[b,C]=await Promise.all([se(n.def.workspace),re(n.def.workspace)]);if(b.byId.size===0&&C.recipes.length===0){let[R,ne]=await Promise.all([se(process.cwd()),re(process.cwd())]);d={refs:R,recipes:ne}}else d={refs:b,recipes:C};this.referencesCache.set(u,d)}let y=Pe({agentId:e.agentId,intentTags:x?.path,message:e.message},d.recipes,d.refs);y.cards.length>0&&(me=Re(y.cards,500*4)),y.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${y.unresolvedIds.join(", ")}`)}catch(u){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${u?.message||u}`)}let pe=this.sessions.getCrossSessionSummary(e.agentId,g,h,e.message),fe,U=je(e.message);if(U)try{let u=this.sessions.recallTurns({agentId:e.agentId,channel:g,chatId:h,lookbackDays:U.lookbackDays,limit:12});if(u.turns.length>0){let d=[`[Long-memory recall \u2014 last ${U.lookbackDays}d on this chat (cue-triggered)]`],y=[...u.turns].sort((b,C)=>b.ts.localeCompare(C.ts));for(let b of y){let C=b.ts.slice(11,16)+" "+b.day,R=b.role==="user"?b.senderName||"User":b.senderName||"Agent";d.push(`${C} ${R}: ${b.content}`)}u.hasMore&&d.push(`[\u2026${u.totalScanned-u.turns.length}+ older turns available \u2014 call /recall with before=${u.oldestTs} to walk further back]`),d.push("[End of long-memory recall \u2014 respond to the latest message above]"),fe=d.join(`
|
|
65
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${U.lookbackDays}d, turns=${u.turns.length}, scanned=${u.totalScanned}`)}}catch(u){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${u.message}`)}let lt=e.contextStrategy??n.def.contextStrategy??this.config.session.contextStrategy??"layered",ye,be,xe=!1;if(lt==="planner"){try{let{planContext:u}=await import("./context-planner-2RGHJHSO.js"),d=await u({agentId:e.agentId,channel:g,chatId:h,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore});d?(xe=!0,ye=d.sessionHistory,D=d.memoryContext,pe=d.crossChatContext,be=d.debug,this.log(`[${e.agentId}] planner: turns=${d.debug.recentTurns}, mem=${d.debug.memoryIncluded?"yes":"no"}, xchat=${d.debug.crossChatIncluded?"yes":"no"} (${d.debug.planLatencyMs}ms) \u2014 ${d.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(u){this.log(`[${e.agentId}] planner failed (non-fatal): ${u.message} \u2014 falling back to layered (keeping --resume for continuity)`)}xe&&k&&(this.sessions.clearClaudeSessionId(e.agentId,g,h),k=void 0)}let Z=`${e.agentId}:${g}:${h}`,B=De(e.message);B&&(B==="default"?(this.activeSouls.delete(Z),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Z,B),this.log(`[${e.agentId}] Soul switched to: ${B}`)));let dt=this.activeSouls.get(Z),gt=Ae(n.def.workspace,dt),ht=Me(gt),V=[n.def.systemPrompt||"",ht||""].filter(u=>u.trim().length>0).join(`
|
|
66
|
+
|
|
67
|
+
`)||void 0,mt={channel:g,chatId:h,channelScope:e.context?.group?"group":g==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:n.def.name,agentHandle:this.getChannelHandle(e.agentId,g),systemPrompt:n.def.systemPrompt,sender:f,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:p||void 0,references:me,skillInjection:w||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:ye??ut,memoryContext:D||void 0,crossChatContext:pe||void 0,longMemoryRecall:fe||void 0,wikiContext:T,handoverNote:this.buildHandoverNote(e.agentId,g,h),intent:x?{path:x.path,pathLabel:x.pathLabel,pathId:x.pathId,axes:x.axes,leaf:x.leaf,status:x.status}:void 0,message:e.message},ee=Ue(mt),te=(ee?.length??0)+(V?.length??0)+(e.message?.length??0),W={history:ee?.length??0,sysPrompt:V?.length??0,message:e.message?.length??0},we=st(e.agentId,g,h);rt(we,te,W);let Se=it(we);Se&&this.log(`[${e.agentId}] ${Se}`),te>16e3&&this.log(`[${e.agentId}] large context for ${g}:${h}: ${te} bytes (history=${W.history}, sysPrompt=${W.sysPrompt}, message=${W.message})`);let pt={...e,systemPromptAppend:V},O;try{if(n.def.tier==="claude-code"){let d=!!k,b=[ze(d),tt(d)].find(R=>R&&R.abort);if(b){n.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${b.reason}`);let R={content:"",error:b.message,duration:0};if(!t){a.buffer=`[error] ${b.message}`;for(let ne of a.subscribers)try{ne(a.buffer)}catch{}}return O=R,R}Ve();let C=nt();C&&this.log(`[${e.agentId}] ${C}`)}let u=await Oe(n.def,pt,this.providers,t,ee,k,m);if(O=u,L().emit("task:completed",{agentId:e.agentId,channel:g,chatId:h,durationMs:Date.now()-S,error:u.error||void 0,inputTokens:u.usage?.inputTokens,outputTokens:u.usage?.outputTokens,cacheReadTokens:u.usage?.cacheReadTokens,cacheCreateTokens:u.usage?.cacheCreateTokens,at:new Date().toISOString()}),!t&&(u.content||u.error)){let d=u.error?`[error] ${u.error}`:u.content;a.buffer=d;for(let y of a.subscribers)try{y(d)}catch{}}if(u.error)n.errors++,this.log(`[${e.agentId}] error: ${u.error}`);else{if(this.sessions.addAgentMessage(e.agentId,g,h,u.content),u.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,g,h,u.claudeSessionId),u.claudeSessionId&&u.usage&&this.sessions.recordTurnUsage(e.agentId,g,h,u.usage),u.usage){let C=(u.usage.inputTokens||0)+(u.usage.cacheReadTokens||0)+(u.usage.cacheCreateTokens||0);C>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${g}:${h}: ${C} total input tokens (input=${u.usage.inputTokens}, cacheRead=${u.usage.cacheReadTokens}, cacheCreate=${u.usage.cacheCreateTokens}) \u2014 next turn will rotate`)}if(u.content.length>50){try{let C=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:C,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:g,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
68
|
+
|
|
69
|
+
Agent: ${u.content}`})}catch{}Te(e.agentId,e.message,u.content,{channel:g,chatId:h,sender:f},this.memoryStore).catch(()=>{}),Je(e.agentId,e.message,u.content,{channel:g,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let d=u.billedModel||e.model||n.def.model,y=e.context?.channel,b=y&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${y}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,u.duration||0,u.usage,e.message.length,u.content.length,!1,d,y,b),this.log(`[${e.agentId}] completed in ${u.duration}ms`+(u.tokensUsed?` (${u.tokensUsed} tokens)`:""))}return u}catch(u){return n.errors++,this.log(`[${e.agentId}] unexpected error: ${u.message}`),O={content:"",error:u.message},O}finally{n.activeTasks--;let u=n.runningTasks.findIndex(d=>d.id===c.id);u!==-1&&n.runningTasks.splice(u,1),a.done=!0,a.endedAt=new Date;for(let d of a.subscribers)try{d(`
|
|
70
|
+
[task finished]
|
|
71
|
+
`)}catch{}a.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(c.id),un).unref?.();try{let d=a.endedAt,y={id:c.id,agentId:e.agentId,channel:c.channel,chatId:c.chatId,sender:c.sender,message:e.message||"",startedAt:c.startedAt.toISOString(),endedAt:d.toISOString(),durationMs:d.getTime()-c.startedAt.getTime(),ok:!O?.error,error:O?.error,responseText:O?.content||"",transcript:a.buffer};this.persistTaskRecord(y);let b=(y.responseText||y.error||"").trim();if(b){let C=b.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:C,at:d,ok:y.ok})}}catch(d){this.log(`[${e.agentId}] task history persist failed: ${d?.message}`)}this.messageQueue.markDone(e.agentId,s,i).then(d=>{if(d.length!==0){this.log(`[${e.agentId}] flushing ${d.length} queued message(s)`);for(let y of d)this.execute({message:y.text,agentId:e.agentId,context:y.originalContext||{channel:y.channel,sender:y.sender,chatId:y.chatId}}).catch(b=>{this.log(`[${e.agentId}] queued message failed: ${b.message}`)})}}).catch(d=>{this.log(`[${e.agentId}] queue flush failed: ${d.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=$(process.cwd(),j,this.safe(e.agentId),t);_(n)||on(n,{recursive:!0});let s=$(n,`${this.safe(e.id)}.json`);cn(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 i=new Array(t).fill(0),o=n-t*36e5,c=$(process.cwd(),j,this.safe(e));if(!_(c))return this.sparklineCache.set(e,{hourly:i,at:n}),i;let a=new Date(n).toISOString().slice(0,10),l=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let g of[l,a]){let h=$(c,g);if(_(h))try{for(let f of P(h)){if(!f.endsWith(".json"))continue;let S=f.split("-")[0],x=parseInt(S,10);if(!Number.isFinite(x)||x<o||x>n)continue;let v=Math.floor((n-x)/36e5),T=t-1-v;T>=0&&T<t&&i[T]++}}catch{}}return this.sparklineCache.set(e,{hourly:i,at:n}),i}hydrateLastSummariesFromDisk(){let e=$(process.cwd(),j);if(!_(e))return 0;let t=0;for(let n of P(e)){let s=$(e,n),i;try{i=P(s).filter(o=>/^\d{4}-\d{2}-\d{2}$/.test(o)).sort().reverse()}catch{continue}e:for(let o of i){let c=$(s,o),a;try{a=P(c).filter(l=>l.endsWith(".json")).sort().reverse()}catch{continue}for(let l of a)try{let m=JSON.parse(ge($(c,l),"utf-8")),g=(m.responseText||m.error||"").trim();if(!g)continue;let h=g.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(m.agentId,{text:h,at:new Date(m.endedAt),ok:m.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=ln){let t=$(process.cwd(),j);if(!_(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=0;for(let i of P(t)){let o=$(t,i),c;try{c=P(o)}catch{continue}for(let a of c){let l=Date.parse(a+"T00:00:00Z");if(!(Number.isNaN(l)||l>=n))try{an($(o,a),{recursive:!0,force:!0}),s++}catch{}}}return s}listTaskHistory(e,t=50){let n=$(process.cwd(),j,this.safe(e));if(!_(n))return[];let s=P(n).filter(o=>/^\d{4}-\d{2}-\d{2}$/.test(o)).sort().reverse(),i=[];for(let o of s){if(i.length>=t)break;let c=$(n,o),a;try{a=P(c).filter(l=>l.endsWith(".json"))}catch{continue}a.sort().reverse();for(let l of a){if(i.length>=t)break;try{let m=JSON.parse(ge($(c,l),"utf-8")),{transcript:g,responseText:h,...f}=m;i.push(f)}catch{}}}return i}getTaskRecord(e,t){let n=$(process.cwd(),j,this.safe(e));if(!_(n))return null;let s=this.safe(t),i=P(n).filter(o=>/^\d{4}-\d{2}-\d{2}$/.test(o)).sort().reverse();for(let o of i){let c=$(n,o,`${s}.json`);if(_(c))try{return JSON.parse(ge(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{wt as a,Tt as b,vt as c,Oe as d,L as e,us as f,ls as g,at as h};
|
|
72
|
+
//# sourceMappingURL=chunk-BTAEYL3P.js.map
|