agentix-cli 0.16.0 → 0.17.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-4AOMVXRJ.js +2 -0
- package/dist/board-dashboard-CXIVJKDP.js +7282 -0
- package/dist/board-dashboard-CXIVJKDP.js.map +1 -0
- package/dist/chunk-34NG7UDX.js +11 -0
- package/dist/chunk-34NG7UDX.js.map +1 -0
- package/dist/chunk-4HP6UC2X.js +13 -0
- package/dist/chunk-4HP6UC2X.js.map +1 -0
- package/dist/chunk-5WNGHDFC.js +164 -0
- package/dist/chunk-5WNGHDFC.js.map +1 -0
- package/dist/{chunk-7MBTMCKY.js → chunk-63UYRJIC.js} +2 -2
- package/dist/chunk-6PPIFDOQ.js +1742 -0
- package/dist/chunk-6PPIFDOQ.js.map +1 -0
- package/dist/chunk-ABCHHNG6.js +625 -0
- package/dist/chunk-ABCHHNG6.js.map +1 -0
- package/dist/chunk-AFRHKA7B.js +2 -0
- package/dist/chunk-AFRHKA7B.js.map +1 -0
- package/dist/chunk-CDNWCYF7.js +2 -0
- package/dist/chunk-CDNWCYF7.js.map +1 -0
- package/dist/{chunk-6MKAXEE5.js → chunk-EKTPCSN4.js} +2 -2
- package/dist/{chunk-6MKAXEE5.js.map → chunk-EKTPCSN4.js.map} +1 -1
- package/dist/chunk-EW27SCCC.js +2 -0
- package/dist/chunk-EW27SCCC.js.map +1 -0
- package/dist/chunk-HCFSHGK4.js +46 -0
- package/dist/chunk-HCFSHGK4.js.map +1 -0
- package/dist/chunk-HHJGKD5B.js +71 -0
- package/dist/chunk-HHJGKD5B.js.map +1 -0
- package/dist/{chunk-YI2T5QYB.js → chunk-MBEQASP3.js} +2 -2
- package/dist/chunk-N67JZAXU.js +2 -0
- package/dist/chunk-N67JZAXU.js.map +1 -0
- package/dist/{chunk-FLOGK2U7.js → chunk-SRHLXZRF.js} +2 -2
- package/dist/chunk-TT2Q7YMZ.js +118 -0
- package/dist/chunk-TT2Q7YMZ.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-XDJSYQST.js +6 -0
- package/dist/chunk-XDJSYQST.js.map +1 -0
- package/dist/chunk-YPOELN6Z.js +798 -0
- package/dist/chunk-YPOELN6Z.js.map +1 -0
- 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-X46EQEPS.js} +6 -6
- package/dist/compaction-X46EQEPS.js.map +1 -0
- package/dist/{config-LN6JEHMF.js → config-KCYHMKCT.js} +2 -2
- package/dist/config-mutator-QP4GLBOE.js +2 -0
- package/dist/context-planner-G2J7FNNU.js +17 -0
- package/dist/context-planner-G2J7FNNU.js.map +1 -0
- package/dist/editor-chat-R54E65W5.js +137 -0
- package/dist/editor-chat-R54E65W5.js.map +1 -0
- package/dist/heal-JDXUPRET.js +2 -0
- package/dist/inbox-L5ZZ623Y.js +315 -0
- package/dist/inbox-L5ZZ623Y.js.map +1 -0
- package/dist/index.d.ts +2917 -1781
- package/dist/index.js +23 -53
- package/dist/index.js.map +1 -1
- package/dist/ingest-whatsapp-NS4OWDOU.js +6 -0
- package/dist/ingest-whatsapp-NS4OWDOU.js.map +1 -0
- package/dist/memory-extract-WH4FZ456.js +2 -0
- package/dist/processes-XF5CV4LK.js +256 -0
- package/dist/processes-XF5CV4LK.js.map +1 -0
- package/dist/program-FFWEILAS.js +2 -0
- package/dist/providers-AKQ4HTB4.js +2 -0
- package/dist/registry-IFMDJWQ7.js +2 -0
- package/dist/scheduler-63D5KFO7.js +2 -0
- package/dist/slack-PSQLVTGB.js +3 -0
- package/dist/slack-PSQLVTGB.js.map +1 -0
- package/dist/store-5MJOO74U.js +2 -0
- package/dist/store-5MJOO74U.js.map +1 -0
- package/dist/task-store-NM7VKNLE.js +2 -0
- package/dist/task-store-NM7VKNLE.js.map +1 -0
- package/dist/telegram-W4SLFMNY.js +3 -0
- package/dist/telegram-W4SLFMNY.js.map +1 -0
- package/dist/timers-PCB4ZIBD.js +2 -0
- package/dist/timers-PCB4ZIBD.js.map +1 -0
- package/dist/types-C7IFH42Z.js +2 -0
- package/dist/types-C7IFH42Z.js.map +1 -0
- package/dist/usage-dashboard-AXPXB2KP.js +803 -0
- package/dist/usage-dashboard-AXPXB2KP.js.map +1 -0
- package/dist/web/workflow-editor.global.js +1427 -0
- package/dist/web/workflow-editor.global.js.map +1 -0
- package/dist/whatsapp-DCHRBRVV.js +3 -0
- package/dist/whatsapp-DCHRBRVV.js.map +1 -0
- package/dist/workspace-setup-C4VB3QZV.js +2 -0
- package/dist/workspace-setup-C4VB3QZV.js.map +1 -0
- package/package.json +9 -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-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-RB7265LO.js +0 -12
- package/dist/chunk-RB7265LO.js.map +0 -1
- package/dist/compaction-JBZZ7I7Y.js.map +0 -1
- package/dist/config-mutator-24TH7PHM.js +0 -2
- package/dist/heal-WKY5I4KB.js +0 -2
- package/dist/memory-extract-AD7KMRPC.js +0 -2
- package/dist/providers-VUIWO3ZK.js +0 -2
- package/dist/registry-ASC2QS5K.js +0 -2
- package/dist/scheduler-A3TQOCKT.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-4AOMVXRJ.js.map} +0 -0
- /package/dist/{chunk-7MBTMCKY.js.map → chunk-63UYRJIC.js.map} +0 -0
- /package/dist/{chunk-YI2T5QYB.js.map → chunk-MBEQASP3.js.map} +0 -0
- /package/dist/{chunk-FLOGK2U7.js.map → chunk-SRHLXZRF.js.map} +0 -0
- /package/dist/{chunk-QZP65I2H.js.map → chunk-ZE2YFX4K.js.map} +0 -0
- /package/dist/{config-LN6JEHMF.js.map → config-KCYHMKCT.js.map} +0 -0
- /package/dist/{config-mutator-24TH7PHM.js.map → config-mutator-QP4GLBOE.js.map} +0 -0
- /package/dist/{heal-WKY5I4KB.js.map → heal-JDXUPRET.js.map} +0 -0
- /package/dist/{memory-extract-AD7KMRPC.js.map → memory-extract-WH4FZ456.js.map} +0 -0
- /package/dist/{providers-VUIWO3ZK.js.map → program-FFWEILAS.js.map} +0 -0
- /package/dist/{registry-ASC2QS5K.js.map → providers-AKQ4HTB4.js.map} +0 -0
- /package/dist/{scheduler-A3TQOCKT.js.map → registry-IFMDJWQ7.js.map} +0 -0
- /package/dist/{workspace-setup-ZWTT42XT.js.map → scheduler-63D5KFO7.js.map} +0 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import{a as fe}from"./chunk-5F3J55LG.js";import{a as pe}from"./chunk-34NG7UDX.js";import{a as ye,b as be,d as xe}from"./chunk-WJXU5F4Z.js";import{b as me}from"./chunk-LEIYC3BF.js";import{b as ge,c as he}from"./chunk-WZEYII2S.js";import{a as de}from"./chunk-63UYRJIC.js";import{c as W,d as B}from"./chunk-QOYAX2FT.js";import{execa as nt}from"execa";import{execFile as st}from"child_process";function H(i){let e=(i||"").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,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}:r==="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}:r==="permission_error"||a===403?{kind:"permission",retryable:!1,message:o||"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: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 N(i){return i.fix?`${i.message} \u2014 ${i.fix}`:i.message}function V(i,e,t){let n=[];if(e.context&&!t){let s=e.context,r=["","[Environment]"],o=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}`),o&&(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 l=a.handle?` (mention: ${a.handle})`:"",h=a.role?` \u2014 ${a.role}`:"";r.push(`\u2022 ${a.name}${l}${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 we(i,e,t,n,s,r){let o=["-p",e,"--output-format",t?"stream-json":"json"];t&&o.push("--verbose"),n&&o.push("--resume",n);let c=s||i.model;return c&&o.push("--model",c),i.permissionMode==="bypassPermissions"&&o.push("--dangerously-skip-permissions"),r&&r.trim().length>0&&o.push("--append-system-prompt",r),o}function rt(i){try{let e=JSON.parse(i);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 it(i){try{let e=JSON.parse(i),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:i}}}async function ot(i,e,t,n){let s=Date.now(),r=V(i,e,t),o=we(i,r,!1,n,e.model,e.systemPromptAppend);try{let c=Math.max(6e4,(i.maxExecutionMinutes??20)*6e4),{stdout:a,stderr:l,exitCode:h}=await new Promise((p,b)=>{st("claude",o,{cwd:i.workspace,timeout:c,maxBuffer:10485760,env:{...process.env,HOME:process.env.HOME||"/home/"+(process.env.USER||"user")}},($,I,k)=>{p({stdout:I||"",stderr:k||"",exitCode:$?$.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 "${i.name||"this agent"}" if tasks need longer.`:p=l?.trim()||`Claude Code exited with code ${h}`,{content:"",error:N(H(p)),duration:Date.now()-s}}let g=rt(a);if(g)return{content:"",error:N(H(g)),duration:Date.now()-s};let m=it(a);return{content:m.text,duration:Date.now()-s,claudeSessionId:m.sessionId,usage:m.usage,billedModel:m.billedModel}}catch(c){return console.error(`[runtime] execFile threw: ${c.message}`),{content:"",error:c.message||"Claude Code failed",duration:Date.now()-s}}}async function at(i,e,t,n,s,r){let o=Date.now(),c=V(i,e,n),a=we(i,c,!0,s,e.model,e.systemPromptAppend),l="",h,g,m,p;try{let b=Math.max(6e4,(i.maxExecutionMinutes??20)*6e4),w=nt("claude",a,{cwd:i.workspace,timeout:b,reject:!1,env:process.env,buffer:!1,stdin:"ignore"});if(w.stdout){let I="";w.stdout.on("data",k=>{I+=k.toString();let C=I.split(`
|
|
4
|
+
`);I=C.pop()||"";for(let D of C)if(D.trim())try{let f=JSON.parse(D);if(r)try{r(f)}catch{}if(f.type==="assistant"&&f.message?.content){for(let x of f.message.content)if(x.type==="text"&&x.text){let R=x.text.slice(l.length);R&&(l=x.text,t(R,l))}}if(f.type==="content_block_delta"&&f.delta?.text&&(l+=f.delta.text,t(f.delta.text,l)),f.type==="result"&&f.result){if(f.is_error&&typeof f.result=="string")p=f.result;else{let x=(typeof f.result=="string",f.result);if(typeof x=="string"&&x.length>l.length){let R=x.slice(l.length);l=x,R&&t(R,l)}}f.usage&&(g={inputTokens:f.usage.input_tokens||0,outputTokens:f.usage.output_tokens||0,cacheReadTokens:f.usage.cache_read_input_tokens||0,cacheCreateTokens:f.usage.cache_creation_input_tokens||0}),typeof f.model=="string"&&(h=f.model),typeof f.session_id=="string"&&(m=f.session_id)}f.type==="system"&&f.subtype==="init"&&(typeof f.model=="string"&&(h=f.model),typeof f.session_id=="string"&&(m=f.session_id))}catch{D.trim()&&!D.startsWith("{")&&(l+=D+`
|
|
5
|
+
`,t(D+`
|
|
6
|
+
`,l))}})}let $=await w;if(!l&&$.stdout&&(l=typeof $.stdout=="string"?$.stdout:""),$.exitCode!==0&&!l){let I=typeof $.stderr=="string"?$.stderr:"",k=$,C;return k.timedOut?C=`Claude Code timed out after ${Math.round(b/6e4)}m. Bump agent.maxExecutionMinutes for "${i.name||"this agent"}" if tasks need longer.`:k.signal?C=I.trim()||`Claude Code killed by signal ${k.signal}`:C=I.trim()||`Claude Code exited with code ${k.exitCode??"unknown"}`,{content:"",error:N(H(C)),duration:Date.now()-o}}return p?{content:"",error:N(H(p)),duration:Date.now()-o,usage:g,billedModel:h,claudeSessionId:m}:{content:l,duration:Date.now()-o,usage:g,billedModel:h,claudeSessionId:m}}catch(b){return{content:l||"",error:N(H(b.message)),duration:Date.now()-o,usage:g,billedModel:h,claudeSessionId:m}}}async function ct(i,e,t,n){let s=Date.now();try{let r=await import("@anthropic-ai/claude-agent-sdk"),{query:o}=r,c=V(i,e,n),a="",l=o({prompt:c,options:{model:e.model||i.model,cwd:i.workspace,permissionMode:"bypassPermissions"}});for await(let h of l)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 ut(i,e,t,n){let s=Date.now();try{let{generate:r}=await import("./agent-4AOMVXRJ.js"),o=i.provider||"claude-code",c=n?`${n}
|
|
7
|
+
|
|
8
|
+
${e.message}`:e.message,a=await r({task:c,cwd:i.workspace,provider:o,model:e.model||i.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 Se(i,e,t,n,s,r,o){switch(i.tier){case"claude-code":return n?at(i,e,n,s,r,o):ot(i,e,s,r);case"sdk":{let c=i.provider||"claude",a=t[c]?.apiKey;return a?ct(i,e,a,s):{content:"",error:`No API key for provider "${c}". Configure providers.${c}.apiKey`}}case"orchestrator":{let c=i.provider||"claude-code",a=t[c]?.apiKey;return ut(i,e,a,s)}default:return{content:"",error:`Unknown tier: ${i.tier}`}}}import{readFileSync as Te,writeFileSync as lt,mkdirSync as dt,existsSync as ve,readdirSync as gt}from"fs";import{resolve as ee}from"path";var ht=12e3,$e=30,mt=45,pt=15,ft=18e4,yt="[Compacted conversation summary",bt=[/\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 xt(i){return i?bt.some(e=>e.test(i)):!1}function Ie(i,e,t,n){if(i.length===0)return!1;let s=i[i.length-1];return s.role===e&&(s.name??"")===t&&s.content===n}function wt(i){let e=i.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=ee(e,".agentx/sessions"),ve(this.sessionsDir)||dt(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??mt),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??pt),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??ft)}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 ee(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(Te(r,"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,r){let o=this.getSession(e,t,n);Ie(o.messages,"user",s,r)||(o.messages.push({role:"user",name:s,content:r,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}addAgentMessage(e,t,n,s){let r=this.getSession(e,t,n);Ie(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})]`],o="";for(let c of s.messages){let a=wt(c.timestamp);a!==o&&(r.push(`\u2014 ${a} \u2014`),o=a);let l=c.name||(c.role==="user"?"User":"Agent");r.push(`${l}: ${c.content}`)}return r.push("[End of history \u2014 respond to the latest message above]"),r.push(""),r.join(`
|
|
9
|
+
`)}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!==""&&!xt(s))return"";let r=new Date().toISOString().slice(0,10),o=this.sessionKey(e,t,n);try{let c=gt(this.sessionsDir).filter(l=>l.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&l.includes(r)&&l.endsWith(".json")),a=[];for(let l of c)try{let h=JSON.parse(Te(ee(this.sessionsDir,l),"utf-8"));if(h.id===o||h.messages.length===0)continue;let g=h.messages.slice(-4),p=!h.chatId.startsWith("-")&&/^\d+$/.test(h.chatId)?"DM":h.chatId,b=g.map(w=>` [${w.timestamp.slice(11,16)}] ${w.name||w.role}: ${w.content.slice(0,200)}`);a.push(`From ${p} (${h.channel}):
|
|
10
|
+
${b.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:o,compactSession:c,applyCompaction:a}=await import("./compaction-X46EQEPS.js");if(!o(r.messages))return{compacted:!1};let l=await c(r.messages,e,s);return l.compactedCount===0?{compacted:!1}:(r.messages=a(r.messages,l),r.updatedAt=new Date().toISOString(),this.save(r),{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(yt)}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){e.messages.length>$e&&(e.messages=e.messages.slice(-$e));let t=e.messages.reduce((n,s)=>n+s.content.length,0);for(;t>ht&&e.messages.length>2;){let n=e.messages.shift();t-=n.content.length}}save(e){try{let t=this.sessionFile(e.id);lt(t,JSON.stringify(e,null,2))}catch{}}};var K=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),o=t-6e4,c=r.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(r.length>=this.maxPerHour){let a=r[0],l=Math.max(1e3,a+36e5-t);return{allowed:!1,reason:`Rate limit: ${r.length}/${this.maxPerHour} per hour`,waitMs:l}}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 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)`};r&&(r=!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 St={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,intent:200,artifacts:500,memory:600,history:1200,"cross-chat":800,wiki:1e3}},ke=4;function Ce(i,e=St){let t=Tt(i,e);t.sort((o,c)=>o.priority-c.priority);let n=[],s=0,r=e.totalBudget*ke;for(let o of t){if(!o.content)continue;let c=o.maxTokens*ke,a=o.content.length>c?o.content.slice(0,c)+"...":o.content;if(s+a.length>r){let l=r-s;l>100&&n.push(a.slice(0,l)+"...");break}n.push(a),s+=a.length}return n.join(`
|
|
13
|
+
|
|
14
|
+
`)}function Tt(i,e){let t=(o,c)=>e.layerBudgets?.[o]??c,n=[];if(n.push(vt(i,t("channel",200))),n.push($t(i,t("scope",200))),i.landscape&&n.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:i.landscape,tags:["landscape","world-model"]}),i.systemPrompt&&n.push({name:"identity",priority:4,maxTokens:t("identity",200),content:i.systemPrompt.split(`
|
|
15
|
+
`)[0],tags:["identity",i.agentId]}),i.bootstrapContext&&n.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:i.bootstrapContext,tags:["bootstrap","identity","personality"]}),i.intent&&i.intent.path.length>0){let o=[`[Intent path: ${i.intent.pathLabel}${i.intent.status==="pending"?" (pending approval)":""}]`],c=i.intent.path[i.intent.path.length-1],a=i.intent.axes?.[c];if(a&&Object.keys(a).length){let l=Object.entries(a).map(([h,g])=>` ${h}: ${g}`).join(`
|
|
16
|
+
`);o.push(l)}i.intent.leaf?.input&&o.push(` input: ${i.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:o.join(`
|
|
17
|
+
`),tags:["intent",...i.intent.path]})}else{let o=It(i.message);o.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${o.join(", ")}]`,tags:o})}let s=[];i.replyToText&&s.push(`[Replying to]: ${i.replyToText.slice(0,300)}`),i.mediaPath&&(s.push(`[Attached file: ${i.mediaPath}]`),s.push(`[File type: ${i.mediaType||"unknown"}]`),i.mediaType?.startsWith("image/")?s.push("Please view this image and respond to it."):i.mediaType?.startsWith("audio/")&&s.push("Please transcribe this audio and respond.")),i.issueMR&&s.push(`[${i.issueMR.type} #${i.issueMR.iid}: ${i.issueMR.title}]`),s.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:s.join(`
|
|
18
|
+
`),tags:["artifacts",...i.mediaType?["media"]:[]]}),i.skillInjection&&n.push({name:"skills",priority:6.2,maxTokens:t("skills",2e3),content:i.skillInjection,tags:["skills","auto-inject"]}),i.patternContext&&n.push({name:"patterns",priority:6.3,maxTokens:t("patterns",400),content:i.patternContext,tags:["patterns","behavioral","self-improving"]}),i.memoryContext&&n.push({name:"memory",priority:6.5,maxTokens:t("memory",600),content:i.memoryContext,tags:["memory","persistent"]});let r=i.groupHistory||i.sessionHistory;if(r&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:r,tags:["history","conversation"]}),i.crossChatContext&&n.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:i.crossChatContext,tags:["history","cross-chat"]}),i.handoverNote){let o=[`[Handover] You are taking over this conversation from ${i.handoverNote.fromAgent}.`];i.handoverNote.summary&&o.push(`Operator summary: ${i.handoverNote.summary}`),o.push(`Handover time: ${i.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:o.join(`
|
|
19
|
+
`),tags:["handover",i.handoverNote.fromAgent]})}return i.wikiContext&&n.push({name:"wiki",priority:8,maxTokens:t("wiki",1e3),content:i.wikiContext,tags:["wiki","knowledge"]}),n}function vt(i,e){let t=[`Channel: ${i.channel}`],n=[],s=[i.channel];switch(i.channel){case"telegram":i.agentHandle&&t.push(`Your handle: ${i.agentHandle}`),t.push(`From: ${i.sender}`),i.senderId&&t.push(`Telegram user ID: ${i.senderId}`),i.senderUsername&&t.push(`Username: @${i.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: ${i.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: ${i.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: ${i.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:i.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(`
|
|
20
|
+
`),tags:s,rules:n}}function $t(i,e){let t=[],n=[];if(i.channelScope==="group"&&i.groupName?(t.push(`Group: ${i.groupName}`),n.push("group",i.groupName)):i.channelScope==="project"&&i.projectPath?(t.push(`Project: ${i.projectPath}`),n.push("project",i.projectPath)):i.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),i.channelMeta){let s=i.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(`
|
|
21
|
+
`),tags:n}}function It(i){let e=[],t=i.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 kt,writeFileSync as Ae,appendFileSync as Ct,mkdirSync as At,existsSync as Me}from"fs";import{resolve as te}from"path";var Pe=200,Mt=7,Q=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=te(e,".agentx/memory"),Me(this.memoryDir)||At(this.memoryDir,{recursive:!0})}filePath(e){return te(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()};Ct(this.filePath(e),JSON.stringify(n)+`
|
|
22
|
+
`)}getAll(e){let t=this.filePath(e);if(!Me(t))return[];try{return kt(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 r=s.map(p=>`${p.keywords.join(" ")} ${p.content}`),o=te(this.memoryDir,`${t}_bm25_cache.json`),c=B(r,o),a=W(e,c),l=new Map(a.map(p=>[p.docIndex,p.score])),g=s.map((p,b)=>{let w=l.get(b)??0;return p.category==="secret"&&(w+=2),p.category==="commitment"&&(w+=1),{memory:p,score:w}}).filter(p=>p.score>0);if(g.length===0)return s.slice(-n);let m=g.sort((p,b)=>b.score-p.score).slice(0,n).map(p=>p.memory);if(m.length>0)try{this.recordAccess(t,m.map(p=>p.id))}catch{}return m}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),r=!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(),r=!0}r&&Ae(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(r=>r.category==="task-state"?!1:r.nextReview?new Date(r.nextReview).getTime()<=s:!0).sort((r,o)=>!r.nextReview&&o.nextReview?-1:r.nextReview&&!o.nextReview?1:r.nextReview&&o.nextReview?new Date(r.nextReview).getTime()-new Date(o.nextReview).getTime():(r.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 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(`
|
|
27
|
+
`)}hasSimilar(e,t){let n=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let c=o.content.toLowerCase();return r.filter(l=>c.includes(l)).length>=r.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let n=Date.now(),s=Mt*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>Pe&&(t=t.slice(-Pe));let r=this.filePath(e);Ae(r,t.map(o=>JSON.stringify(o)).join(`
|
|
28
|
+
`)+`
|
|
29
|
+
`)}};var G=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 o={text:r.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
|
|
30
|
+
`),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([o]),[o]}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 Pt,writeFileSync as De,appendFileSync as Dt,mkdirSync as Rt,existsSync as Re}from"fs";import{resolve as ne}from"path";var _e=50,_t="claude-haiku-4-20250514",Ot=`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: []`,J=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=ne(e,".agentx/patterns"),Re(this.patternsDir)||Rt(this.patternsDir,{recursive:!0})}filePath(e){return ne(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!Re(t))return[];try{return Pt(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()};Dt(this.filePath(e),JSON.stringify(n)+`
|
|
48
|
+
`)}findRelevant(e,t,n=5){let s=this.getAll(t);if(s.length===0)return[];let r=s.map(h=>`${h.context} ${h.pattern}`),o=ne(this.patternsDir,`${t}_bm25_cache.json`),c=B(r,o),l=W(e,c).slice(0,n).map(h=>s[h.docIndex]).filter(h=>h.confidence>=.3);return l.length>0&&this.recordAccess(t,l.map(h=>h.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(r=>r.length>3);return n.some(r=>{let o=r.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),r=!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),r=!0);r&&De(this.filePath(e),n.map(o=>JSON.stringify(o)).join(`
|
|
50
|
+
`)+`
|
|
51
|
+
`)}prune(e){let t=this.getAll(e);t.length<=_e||(t.sort((n,s)=>s.confidence*s.accessCount-n.confidence*n.accessCount),t=t.slice(0,_e),De(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
52
|
+
`)+`
|
|
53
|
+
`))}};async function Oe(i,e,t,n,s){if(e.length<30&&t.length<100)return;let{createProvider:r}=await import("./providers-AKQ4HTB4.js"),a=(await r("claude").generate([{role:"system",content:Ot},{role:"user",content:`User: ${e.slice(0,500)}
|
|
54
|
+
|
|
55
|
+
Agent: ${t.slice(0,1e3)}`}],{model:_t,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 h of l)s.hasSimilar(i,h.pattern)||s.addPattern(i,{agentId:i,pattern:h.pattern,context:h.context,confidence:h.confidence||.5,source:n});Math.random()<.05&&s.prune(i)}}import{readFileSync as Ht}from"fs";import{homedir as Nt}from"os";import{join as Et}from"path";var L=null,jt=6e4;function Lt(){try{let i=Et(Nt(),".claude.json"),e=Ht(i,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function Ft(i,e=Date.now()){if(!i)return{available:!0,checkedAt:e,unknown:!0};let t=typeof i.cachedExtraUsageDisabledReason=="string"?i.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function Ut(i=!1){let e=Date.now();return!i&&L&&e-L.checkedAt<jt||(L=Ft(Lt(),e)),L}function He(i){let e=Ut();return e.available||i?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 Ne={warnRatio:.8},v={...Ne},Wt=5*60*60*1e3,Bt=60*60*1e3,O=[];function Ee(i){v={...Ne,...i||{}}}function je(i){let e=i-Wt,t=0;for(;t<O.length&&O[t]<e;)t++;t>0&&O.splice(0,t)}function Le(i=Date.now()){je(i),O.push(i)}function Fe(i=Date.now()){je(i);let e=i-Bt,t=0;for(let r=O.length-1;r>=0&&O[r]>=e;r--)t++;let n=O.length,s={lastHour:t,last5h:n,maxPerHour:v.maxPerHour,maxPer5h:v.maxPer5h};return v.maxPerHour&&v.maxPerHour>0&&(s.hourlyRatio=t/v.maxPerHour),v.maxPer5h&&v.maxPer5h>0&&(s.fiveHourRatio=n/v.maxPer5h),s}function Ue(i,e=Date.now()){let t=Fe(e);return i?null:v.maxPerHour&&t.lastHour>=v.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${v.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}:v.maxPer5h&&t.last5h>=v.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${v.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 We(i=Date.now()){let e=Fe(i),t=v.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 se=new Map;function Be(i,e,t){return t?`${i}:${e}:${t}`:`${i}:${e}`}function qe(i,e,t,n=Date.now()){let s=se.get(i);s||(s={key:i,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},se.set(i,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:i,timestamp:n,total:e,parts:t}),s.ring.length>100&&s.ring.shift()}function Ke(i){let e=se.get(i);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 ${i}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as P,mkdirSync as qt,readdirSync as M,readFileSync as re,rmSync as Kt,writeFileSync as Qt}from"fs";import{resolve as T}from"path";var Je;function Bn(i){Je=i}function qn(){return Je}var Qe=64*1024,Gt=5*60*1e3,E=".agentx/task-history",Jt=30;function ie(i,e=800){return i.length<=e?i:i.slice(0,e)+` \u2026[+${i.length-e} chars]`}function zt(i,e){let t=0;try{t=i.listArticles(e).length}catch{return""}if(t===0)return"";let n=T(i.baseDir,"_index.md");if(!P(n))return"";let s=process.argv[1]||"dist/cli.js",r=i.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(`
|
|
56
|
+
`)}function Xt(){let i="";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>i.length&&(n+=s.text.slice(i.length),i=s.text);else if(s.type==="thinking"&&typeof s.thinking=="string")n+=`
|
|
58
|
+
\u{1F4AD} ${ie(s.thinking,600)}
|
|
59
|
+
`;else if(s.type==="tool_use"){let r=s.name||"tool",o=s.input?ie(JSON.stringify(s.input),400):"";n+=`
|
|
60
|
+
\u2192 ${r}(${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 r=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}${ie(r,800)}
|
|
62
|
+
`}return n}return t==="result"?`\xB7 done${e.duration_ms?` (${Math.round(e.duration_ms/1e3)}s)`:""}
|
|
63
|
+
`:""}}var Ge=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;messageQueue;classifier;graphStore;handoverStore=new fe;activeSouls=new Map;taskOutputs=new Map;lastSummaries=new Map;sparklineCache=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 me(void 0,void 0,"unified"),this.memoryStore=new Q,this.patternStore=new J,this.rateLimiter=new K,this.tokenTracker=new pe,this.messageQueue=new G,Ee({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new ge({baseDir:T(process.cwd(),e.graph.baseDir),log:(...s)=>t("[graph]",...s)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new he({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 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[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>r&&(s=o,r=l.length)}return s}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[s,r]of this.agents)for(let o of r.def.mentions)if(t.includes(o.toLowerCase())){n.push(s);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}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(`
|
|
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",r=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(n.activeTasks>=n.def.maxConcurrent){let u=n.def.queueMode||"collect",d=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(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,r);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>Qe&&(a.buffer=a.buffer.slice(a.buffer.length-Qe));for(let d of a.subscribers)try{d(u)}catch{}}},h;if(t){let u=Xt();h=d=>{let y=u(d);y&&l(y)}}this.messageQueue.markRunning(e.agentId,s,r),this.log(`[${e.agentId}] executing task (${n.activeTasks}/${n.def.maxConcurrent})`);let g=e.context?.channel||"api",m=e.context?.chatId||e.context?.group||e.context?.sender||"default",p=e.context?.sender||"User";this.sessions.addUserMessage(e.agentId,g,m,p,e.message);let b;if(this.classifier&&g!=="a2a")try{b=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 w=this.wikiHub.getAgentWiki(e.agentId),$=zt(w,e.agentId),I=this.memoryStore.findRelevant(e.message,e.agentId,8),k=this.memoryStore.buildContext(I),C=this.patternStore.findRelevant(e.message,e.agentId,5),D=this.patternStore.buildContext(C),f="";try{let{loadLocalSkills:u,getAutoInjectSkills:d}=await import("./loader-PTCXLJEX.js"),y=await u(n.def.workspace);f=d(y,e.message)}catch{}let x=n.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,g,m):void 0;if(x&&this.sessions.isSessionStale(e.agentId,g,m)&&(this.log(`[${e.agentId}] session stale for ${g}:${m}, starting fresh`),this.sessions.clearClaudeSessionId(e.agentId,g,m),x=void 0),x&&this.sessions.shouldRotateByTierTwo(e.agentId,g,m)){let u=this.sessions.getLastTurnInputTokens(e.agentId,g,m);this.log(`[${e.agentId}] tier-2 rotation for ${g}:${m} (last turn: ${u} input tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),this.sessions.clearClaudeSessionId(e.agentId,g,m),x=void 0}if(x&&this.sessions.shouldRotateByTurns(e.agentId,g,m)){let u=this.sessions.getTurnCount(e.agentId,g,m);this.log(`[${e.agentId}] max-turns rotation for ${g}:${m} (${u} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),this.sessions.clearClaudeSessionId(e.agentId,g,m),x=void 0}try{let u=await this.sessions.compactIfNeeded(e.agentId,g,m,this.memoryStore);if(u.compacted){let d=u.qualityScore??"?",y=u.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${g}:${m} (quality: ${d}%, ${y} entities lost)`),u.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${u.lostEntities.slice(0,5).join(", ")}`),u.drift){let S=u.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(u){this.log(`[${e.agentId}] compaction failed (non-fatal): ${u.message}`)}let R=x?void 0:this.sessions.buildHistoryContext(e.agentId,g,m),oe=this.sessions.getCrossSessionSummary(e.agentId,g,m,e.message),ze=e.contextStrategy??this.config.session.contextStrategy??"layered",ae,ce;if(ze==="planner"){try{let{planContext:u}=await import("./context-planner-G2J7FNNU.js"),d=await u({agentId:e.agentId,channel:g,chatId:m,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore});d?(ae=d.sessionHistory,k=d.memoryContext,oe=d.crossChatContext,ce=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`)}catch(u){this.log(`[${e.agentId}] planner failed (non-fatal): ${u.message} \u2014 falling back to layered`)}x&&(this.sessions.clearClaudeSessionId(e.agentId,g,m),x=void 0)}let z=`${e.agentId}:${g}:${m}`,F=xe(e.message);F&&(F==="default"?(this.activeSouls.delete(z),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(z,F),this.log(`[${e.agentId}] Soul switched to: ${F}`)));let Xe=this.activeSouls.get(z),Ye=ye(n.def.workspace,Xe),Ze=be(Ye),X=[n.def.systemPrompt||"",Ze||""].filter(u=>u.trim().length>0).join(`
|
|
65
|
+
|
|
66
|
+
`)||void 0,Ve={channel:g,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: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:D||void 0,skillInjection:f||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:ae??R,memoryContext:k||void 0,crossChatContext:oe||void 0,wikiContext:$,handoverNote:this.buildHandoverNote(e.agentId,g,m),intent:b?{path:b.path,pathLabel:b.pathLabel,pathId:b.pathId,axes:b.axes,leaf:b.leaf,status:b.status}:void 0,message:e.message},Y=Ce(Ve),Z=(Y?.length??0)+(X?.length??0)+(e.message?.length??0),U={history:Y?.length??0,sysPrompt:X?.length??0,message:e.message?.length??0},ue=Be(e.agentId,g,m);qe(ue,Z,U);let le=Ke(ue);le&&this.log(`[${e.agentId}] ${le}`),Z>16e3&&this.log(`[${e.agentId}] large context for ${g}:${m}: ${Z} bytes (history=${U.history}, sysPrompt=${U.sysPrompt}, message=${U.message})`);let et={...e,systemPromptAppend:X},_;try{if(n.def.tier==="claude-code"){let d=!!x,S=[He(d),Ue(d)].find(j=>j&&j.abort);if(S){n.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${S.reason}`);let j={content:"",error:S.message,duration:0};if(!t){a.buffer=`[error] ${S.message}`;for(let tt of a.subscribers)try{tt(a.buffer)}catch{}}return _=j,j}Le();let A=We();A&&this.log(`[${e.agentId}] ${A}`)}let u=await Se(n.def,et,this.providers,t,Y,x,h);if(_=u,!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,m,u.content),u.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,g,m,u.claudeSessionId),u.claudeSessionId&&u.usage&&this.sessions.recordTurnUsage(e.agentId,g,m,u.usage),u.usage){let A=(u.usage.inputTokens||0)+(u.usage.cacheReadTokens||0)+(u.usage.cacheCreateTokens||0);A>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${g}:${m}: ${A} 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 A=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:A,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:g,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
67
|
+
|
|
68
|
+
Agent: ${u.content}`})}catch{}de(e.agentId,e.message,u.content,{channel:g,chatId:m,sender:p},this.memoryStore).catch(()=>{}),Oe(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,S=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,S),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}`),_={content:"",error:u.message},_}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(`
|
|
69
|
+
[task finished]
|
|
70
|
+
`)}catch{}a.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(c.id),Gt).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:!_?.error,error:_?.error,responseText:_?.content||"",transcript:a.buffer};this.persistTaskRecord(y);let S=(y.responseText||y.error||"").trim();if(S){let A=S.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:A,at:d,ok:y.ok})}}catch(d){this.log(`[${e.agentId}] task history persist failed: ${d?.message}`)}this.messageQueue.markDone(e.agentId,s,r).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(S=>{this.log(`[${e.agentId}] queued message failed: ${S.message}`)})}}).catch(d=>{this.log(`[${e.agentId}] queue flush failed: ${d.message}`)})}}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=T(process.cwd(),E,this.safe(e.agentId),t);P(n)||qt(n,{recursive:!0});let s=T(n,`${this.safe(e.id)}.json`);Qt(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),o=n-t*36e5,c=T(process.cwd(),E,this.safe(e));if(!P(c))return this.sparklineCache.set(e,{hourly:r,at:n}),r;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 m=T(c,g);if(P(m))try{for(let p of M(m)){if(!p.endsWith(".json"))continue;let b=p.split("-")[0],w=parseInt(b,10);if(!Number.isFinite(w)||w<o||w>n)continue;let $=Math.floor((n-w)/36e5),I=t-1-$;I>=0&&I<t&&r[I]++}}catch{}}return this.sparklineCache.set(e,{hourly:r,at:n}),r}hydrateLastSummariesFromDisk(){let e=T(process.cwd(),E);if(!P(e))return 0;let t=0;for(let n of M(e)){let s=T(e,n),r;try{r=M(s).filter(o=>/^\d{4}-\d{2}-\d{2}$/.test(o)).sort().reverse()}catch{continue}e:for(let o of r){let c=T(s,o),a;try{a=M(c).filter(l=>l.endsWith(".json")).sort().reverse()}catch{continue}for(let l of a)try{let h=JSON.parse(re(T(c,l),"utf-8")),g=(h.responseText||h.error||"").trim();if(!g)continue;let m=g.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(h.agentId,{text:m,at:new Date(h.endedAt),ok:h.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Jt){let t=T(process.cwd(),E);if(!P(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=0;for(let r of M(t)){let o=T(t,r),c;try{c=M(o)}catch{continue}for(let a of c){let l=Date.parse(a+"T00:00:00Z");if(!(Number.isNaN(l)||l>=n))try{Kt(T(o,a),{recursive:!0,force:!0}),s++}catch{}}}return s}listTaskHistory(e,t=50){let n=T(process.cwd(),E,this.safe(e));if(!P(n))return[];let s=M(n).filter(o=>/^\d{4}-\d{2}-\d{2}$/.test(o)).sort().reverse(),r=[];for(let o of s){if(r.length>=t)break;let c=T(n,o),a;try{a=M(c).filter(l=>l.endsWith(".json"))}catch{continue}a.sort().reverse();for(let l of a){if(r.length>=t)break;try{let h=JSON.parse(re(T(c,l),"utf-8")),{transcript:g,responseText:m,...p}=h;r.push(p)}catch{}}}return r}getTaskRecord(e,t){let n=T(process.cwd(),E,this.safe(e));if(!P(n))return null;let s=this.safe(t),r=M(n).filter(o=>/^\d{4}-\d{2}-\d{2}$/.test(o)).sort().reverse();for(let o of r){let c=T(n,o,`${s}.json`);if(P(c))try{return JSON.parse(re(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{ot as a,ct as b,ut as c,Se as d,Bn as e,qn as f,Ge as g};
|
|
71
|
+
//# sourceMappingURL=chunk-HHJGKD5B.js.map
|