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