agentix-cli 0.25.0 → 0.26.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/README.md +2 -0
- package/dist/{App-6Y7B3YQH.js → App-BPNHIGUX.js} +2 -2
- package/dist/{ChatApp-KIEUJ2DS.js → ChatApp-6XSSZB4U.js} +2 -2
- package/dist/{agent-QGZIAZMY.js → agent-5QMITZT6.js} +2 -2
- package/dist/{board-dashboard-CQ5F4GPD.js → board-dashboard-M3372FLO.js} +1191 -225
- package/dist/board-dashboard-M3372FLO.js.map +1 -0
- package/dist/{chunk-JXWAGMI2.js → chunk-BTHHSY7D.js} +7 -7
- package/dist/chunk-BTHHSY7D.js.map +1 -0
- package/dist/{chunk-TRJTTBE2.js → chunk-BVGJSPW4.js} +2 -2
- package/dist/{chunk-53GCFZPR.js → chunk-D46VZ7K7.js} +2 -2
- package/dist/{chunk-HA3XI7Z2.js → chunk-E5CXCI33.js} +27 -27
- package/dist/chunk-E5CXCI33.js.map +1 -0
- package/dist/{chunk-FDMWOPEL.js → chunk-K2CAPYES.js} +2 -2
- package/dist/{chunk-TMKLHTCG.js → chunk-METYYZKQ.js} +264 -120
- package/dist/chunk-METYYZKQ.js.map +1 -0
- package/dist/{chunk-Q6YO7LYE.js → chunk-MTAPOCGA.js} +2 -2
- package/dist/{chunk-G57RZCXM.js → chunk-O6YPEOQF.js} +2 -2
- package/dist/{chunk-KUCCW2VG.js → chunk-UHE5FCPB.js} +8 -8
- package/dist/{chunk-LNXCJWOU.js → chunk-V3U4OF7L.js} +2 -2
- package/dist/{chunk-NGSIRE4X.js → chunk-VT5XYFDD.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/client-HGKAC6VP.js +2 -0
- package/dist/{config-7FSZFRTQ.js → config-A4RWEJHV.js} +2 -2
- package/dist/config-mutator-MNSFUN7D.js +2 -0
- package/dist/doctor-3Q36ZFE6.js +2 -0
- package/dist/index.d.ts +58 -1
- package/dist/index.js +1 -1
- package/dist/{program-WVAVJFND.js → program-SAUNRCCD.js} +2 -2
- package/dist/{registry-T36ZIAWV.js → registry-HK3WQ7BS.js} +2 -2
- package/dist/scheduler-6T2SU5ST.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-CQ5F4GPD.js.map +0 -1
- package/dist/chunk-HA3XI7Z2.js.map +0 -1
- package/dist/chunk-JXWAGMI2.js.map +0 -1
- package/dist/chunk-TMKLHTCG.js.map +0 -1
- package/dist/client-GGVVLOOF.js +0 -2
- package/dist/config-mutator-POCOYYJ4.js +0 -2
- package/dist/doctor-DHLBEKA4.js +0 -2
- package/dist/scheduler-GH7TIKYS.js +0 -2
- /package/dist/{App-6Y7B3YQH.js.map → App-BPNHIGUX.js.map} +0 -0
- /package/dist/{ChatApp-KIEUJ2DS.js.map → ChatApp-6XSSZB4U.js.map} +0 -0
- /package/dist/{agent-QGZIAZMY.js.map → agent-5QMITZT6.js.map} +0 -0
- /package/dist/{chunk-TRJTTBE2.js.map → chunk-BVGJSPW4.js.map} +0 -0
- /package/dist/{chunk-53GCFZPR.js.map → chunk-D46VZ7K7.js.map} +0 -0
- /package/dist/{chunk-FDMWOPEL.js.map → chunk-K2CAPYES.js.map} +0 -0
- /package/dist/{chunk-Q6YO7LYE.js.map → chunk-MTAPOCGA.js.map} +0 -0
- /package/dist/{chunk-G57RZCXM.js.map → chunk-O6YPEOQF.js.map} +0 -0
- /package/dist/{chunk-KUCCW2VG.js.map → chunk-UHE5FCPB.js.map} +0 -0
- /package/dist/{chunk-LNXCJWOU.js.map → chunk-V3U4OF7L.js.map} +0 -0
- /package/dist/{chunk-NGSIRE4X.js.map → chunk-VT5XYFDD.js.map} +0 -0
- /package/dist/{client-GGVVLOOF.js.map → client-HGKAC6VP.js.map} +0 -0
- /package/dist/{config-7FSZFRTQ.js.map → config-A4RWEJHV.js.map} +0 -0
- /package/dist/{config-mutator-POCOYYJ4.js.map → config-mutator-MNSFUN7D.js.map} +0 -0
- /package/dist/{doctor-DHLBEKA4.js.map → doctor-3Q36ZFE6.js.map} +0 -0
- /package/dist/{program-WVAVJFND.js.map → program-SAUNRCCD.js.map} +0 -0
- /package/dist/{registry-T36ZIAWV.js.map → registry-HK3WQ7BS.js.map} +0 -0
- /package/dist/{scheduler-GH7TIKYS.js.map → scheduler-6T2SU5ST.js.map} +0 -0
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
import{C as sn,a as zt,e as nn}from"./chunk-
|
|
1
|
+
import{C as sn,a as zt,e as nn}from"./chunk-MTAPOCGA.js";import{c as Kt,e as Qt,f as Xt,h as Yt}from"./chunk-67Q4DCPS.js";import{a as tn}from"./chunk-W4YR2RO2.js";import{a as Le,c as Vt}from"./chunk-D46VZ7K7.js";import{a as je,b as at}from"./chunk-HR4JSRZS.js";import{b as Gt,c as qt,f as Jt}from"./chunk-BFXONUUN.js";import{a as ct,b as Zt}from"./chunk-SR3X25TN.js";import{a as dt,b as en}from"./chunk-53NRX2NA.js";import{e as ie}from"./chunk-DSYKYZMT.js";import{a as Bt}from"./chunk-5U35WAZF.js";import{c as Ne,d as Fe}from"./chunk-QOYAX2FT.js";import{execa as Ge}from"execa";import{execFile as bs}from"child_process";import{StringDecoder as ke}from"string_decoder";import{mkdtempSync as un,readFileSync as ln,rmSync as gn}from"fs";import{join as Ke}from"path";import{tmpdir as pn}from"os";function He(r){let e=(r||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{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};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{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};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,o=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|credit balance (is )?too low|low credit balance/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}:o==="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}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="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}:o==="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}:o==="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 Ue(r){return r.fix?`${r.message} \u2014 ${r.fix}`:r.message}var rn=null;function We(){return rn}function ro(r){rn=r}function Te(r){return`${r.agentId}:${r.channel}:${r.chatId}`}var pe=class extends Error{constructor(t,n,s){super(t);this.scope=n;this.cap=s;this.name="RegistryCapExceeded"}},on=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=Te(e),s=this.handles.get(n);if(s&&s.state()!=="dead")return s.claim?.(),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 pe(`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 pe(`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=Te(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())}hasLive(e){let t=Te(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Te(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 o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let s=Te(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 o=e-s.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/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",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};function K(r){let e=He(r);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(r||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
|
|
2
2
|
`)}return{error:Ue(e),errorKind:e.kind}}function fn(){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 Be(){return`Codex CLI not found on PATH. Install it before starting an agent: npm i -g @openai/codex then verify with codex --version. If you don't intend to use the codex-cli engine, set the agent's tier to "claude-code", "sdk", or "orchestrator" in agentx.json.`}function an(){return`OpenCode CLI not found on PATH. Install it from https://opencode.ai/docs/ and verify with opencode --version. If you don't intend to use the opencode engine, set the agent's tier to "claude-code", "codex-cli", "sdk", or "orchestrator" in agentx.json.`}function ae(r,e,t){let n=[];if(e.context&&!t){let s=e.context,o=["","[Environment]"],i=s.channel==="gitlab"||s.channel?.startsWith("webhook:"),a=s.channel==="telegram";if(s.channel&&o.push(`Channel: ${s.channel}`),s.group&&o.push(`Group: ${s.group}`),s.sender&&o.push(`Message from: ${s.sender}`),s.myHandle&&o.push(`Your handle on this channel: ${s.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&s.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of s.peers){let d=c.handle?` (mention: ${c.handle})`:"",u=c.role?` \u2014 ${c.role}`:"";o.push(`\u2022 ${c.name}${d}${u}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(o.join(`
|
|
3
3
|
`))}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(`
|
|
4
4
|
`)}function hn(r,e,t,n,s,o){let i=["-p",e,"--output-format",t?"stream-json":"json"];t&&i.push("--verbose"),n&&i.push("--resume",n);let a=s||r.model;return a&&i.push("--model",a),r.permissionMode==="bypassPermissions"&&i.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&i.push("--append-system-prompt",o),i}function mn(r,e){return!e||e.trim().length===0?r:`[System]
|
|
5
5
|
${e.trim()}
|
|
6
6
|
|
|
7
7
|
[User]
|
|
8
|
-
${r}`}function xs(r,e,t,n,s){let o=["run","--format","json"],i=t||r.model;return i&&o.push("--model",i),s&&o.push("--session",s),r.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(mn(e,n)),o}function ws(r){if(!r||typeof r!="object"||r.type!=="error")return;let e=r.error?.message??r.error??r.message??r.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function cn(r){return JSON.stringify(r)}function Ts(){let r=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${cn(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[r,"serve","--stdio","--cwd",process.cwd()].map(cn).join(",")}]`]}function yn(r,e,t,n,s,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...Ts()),i||a.push("--color","never");let c=n||r.model;return c&&a.push("--model",c),r.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(mn(e,s)),a}function ut(r,e){let t=je(r.workspace),n=t.HOME||process.env.HOME,s=[t.PATH||"",n?`${n}/.bun/bin`:"",n?`${n}/.local/bin`:"",n?`${n}/.opencode/bin`:"","/opt/homebrew/bin","/usr/local/bin"].filter(Boolean);return t.PATH=Array.from(new Set(s.flatMap(o=>o.split(":")).filter(Boolean))).join(":"),t.AGENTX_AGENT_ID=e.agentId,e.context?.channel&&(t.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(t.AGENTX_CHAT_ID=e.context.chatId),t}function ks(r,e){let t=ut(r,e),n={};if(t.OPENCODE_CONFIG_CONTENT)try{n=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let s={...n.mcp||{}};for(let[i,a]of Object.entries(r.mcp||{}))s[i]=a.type==="http"?{type:"remote",url:a.url,headers:a.headers}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let o=process.argv[1]||"dist/cli.js";return s.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...n,mcp:s}),t}function Is(r){if(!r||typeof r!="object")return;if(typeof r.delta=="string")return r.delta;if(typeof r.text_delta=="string")return r.text_delta;if(typeof r.message=="string"&&/message|delta/i.test(String(r.type||"")))return r.message;if(typeof r.text=="string"&&/message|delta|response/i.test(String(r.type||"")))return r.text;let e=r.item||r.msg||r.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(r.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let n=t.map(s=>typeof s?.text=="string"?s.text:"").join("");if(n)return n}}function ee(...r){for(let e of r)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function lt(r,e=0){if(!r||typeof r!="object"||e>4)return;let t=r.usage||r.token_usage||r.tokenUsage||r.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:ee(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:ee(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:ee(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:ee(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[r.msg,r.message,r.response,r.result,r.item]){let s=lt(n,e+1);if(s)return s}}function bn(r){if(!(!r||typeof r!="object"))return typeof r.model=="string"&&r.model||typeof r.msg?.model=="string"&&r.msg.model||typeof r.message?.model=="string"&&r.message.model||typeof r.response?.model=="string"&&r.response.model||void 0}function gt(r,e=0){if(!(!r||typeof r!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}for(let t of[r.msg,r.message,r.response,r.result,r.item]){let n=gt(t,e+1);if(n)return n}}}function Ss(r){let e=typeof r=="string"?r:r?.toString("utf8")||"",t,n,s,o;for(let i of e.split(`
|
|
8
|
+
${r}`}function xs(r,e,t,n,s){let o=["run","--format","json","--thinking"],i=t||r.model;return i&&o.push("--model",i),s&&o.push("--session",s),r.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(mn(e,n)),o}function ws(r){if(!r||typeof r!="object"||r.type!=="error")return;let e=r.error?.message??r.error??r.message??r.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function cn(r){return JSON.stringify(r)}function Ts(){let r=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${cn(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[r,"serve","--stdio","--cwd",process.cwd()].map(cn).join(",")}]`]}function yn(r,e,t,n,s,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...Ts()),i||a.push("--color","never");let c=n||r.model;return c&&a.push("--model",c),r.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(mn(e,s)),a}function ut(r,e){let t=je(r.workspace),n=t.HOME||process.env.HOME,s=[t.PATH||"",n?`${n}/.bun/bin`:"",n?`${n}/.local/bin`:"",n?`${n}/.opencode/bin`:"","/opt/homebrew/bin","/usr/local/bin"].filter(Boolean);return t.PATH=Array.from(new Set(s.flatMap(o=>o.split(":")).filter(Boolean))).join(":"),t.AGENTX_AGENT_ID=e.agentId,e.context?.channel&&(t.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(t.AGENTX_CHAT_ID=e.context.chatId),t}function ks(r,e){let t=ut(r,e),n={};if(t.OPENCODE_CONFIG_CONTENT)try{n=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let s={...n.mcp||{}};for(let[i,a]of Object.entries(r.mcp||{}))s[i]=a.type==="http"?{type:"remote",url:a.url,headers:a.headers}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let o=process.argv[1]||"dist/cli.js";return s.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...n,mcp:s}),t}function Is(r){if(!r||typeof r!="object")return;if(typeof r.delta=="string")return r.delta;if(typeof r.text_delta=="string")return r.text_delta;if(typeof r.message=="string"&&/message|delta/i.test(String(r.type||"")))return r.message;if(typeof r.text=="string"&&/message|delta|response/i.test(String(r.type||"")))return r.text;let e=r.item||r.msg||r.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(r.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let n=t.map(s=>typeof s?.text=="string"?s.text:"").join("");if(n)return n}}function ee(...r){for(let e of r)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function lt(r,e=0){if(!r||typeof r!="object"||e>4)return;let t=r.usage||r.token_usage||r.tokenUsage||r.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:ee(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:ee(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:ee(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:ee(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[r.msg,r.message,r.response,r.result,r.item]){let s=lt(n,e+1);if(s)return s}}function bn(r){if(!(!r||typeof r!="object"))return typeof r.model=="string"&&r.model||typeof r.msg?.model=="string"&&r.msg.model||typeof r.message?.model=="string"&&r.message.model||typeof r.response?.model=="string"&&r.response.model||void 0}function gt(r,e=0){if(!(!r||typeof r!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}for(let t of[r.msg,r.message,r.response,r.result,r.item]){let n=gt(t,e+1);if(n)return n}}}function Ss(r){let e=typeof r=="string"?r:r?.toString("utf8")||"",t,n,s,o;for(let i of e.split(`
|
|
9
9
|
`))if(i.trim())try{let a=JSON.parse(i);t=lt(a)||t,n=bn(a)||n,s=gt(a)||s,o=xn(a)||o}catch{}return{usage:t,billedModel:n,sessionId:s,apiError:o}}function xn(r){if(!(!r||typeof r!="object")){if(r.type==="error"&&typeof r.message=="string")return dn(r.message);if(r.type==="turn.failed"){let e=r.error?.message??r.error;if(typeof e=="string")return dn(e)}}}function dn(r){let e=r.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),n=t?.error?.message??t?.message;if(typeof n=="string"&&n.trim())return n.trim()}catch{}return e}function Cs(r){let e=r.permissionMode||"default",t=e==="bypassPermissions",n=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:n}}function pt(r,e,t,n,s){let o=Cs(e),i=t||e.model||"<default>",a=n?` resume=${n.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${r} via=${s} model=${i} perm=${o.summary}${a}
|
|
10
|
-
`)}function vs(r){try{let e=JSON.parse(r);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function $s(r){try{let e=JSON.parse(r),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,n=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:n}}catch{return{text:r}}}async function As(r,e,t,n,s){let o=Date.now(),i=ae(r,e,t),a=hn(r,i,!1,n,e.model,e.systemPromptAppend);if(pt(e.agentId,r,e.model,n,"spawn"),s?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let c;try{let d=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),{stdout:u,stderr:l,exitCode:g,killed:m}=await new Promise(
|
|
11
|
-
`);
|
|
12
|
-
`))}catch{
|
|
10
|
+
`)}function vs(r){try{let e=JSON.parse(r);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function $s(r){try{let e=JSON.parse(r),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,n=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:n}}catch{return{text:r}}}async function As(r,e,t,n,s){let o=Date.now(),i=ae(r,e,t),a=hn(r,i,!1,n,e.model,e.systemPromptAppend);if(pt(e.agentId,r,e.model,n,"spawn"),s?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let c;try{let d=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),{stdout:u,stderr:l,exitCode:g,killed:m}=await new Promise(x=>{let p=at(je(r.workspace)),f=!1,D=bs("claude",a,{cwd:r.workspace,timeout:d,maxBuffer:10*1024*1024,env:{...p,HOME:p.HOME||"/home/"+(p.USER||"user")}},(C,T,$)=>{x({stdout:T||"",stderr:$||"",exitCode:C?C.code??1:0,killed:f})});if(D.stdin?.end(),s){let C=()=>{f=!0,c=s.reason?.message||(typeof s.reason=="string"?s.reason:"task cancelled by operator");try{D.kill("SIGTERM")}catch{}setTimeout(()=>{try{D.killed||D.kill("SIGKILL")}catch{}},3e3).unref?.()};s.aborted?C():s.addEventListener("abort",C,{once:!0})}});if(m)return{content:"",error:c||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!u&&g!==0){let x;return g===143?x=`Claude Code timed out after ${Math.round(d/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:g==="ENOENT"||/ENOENT|spawn claude/i.test(l||"")?x=fn():x=l?.trim()||`Claude Code exited with code ${g}`,{content:"",...K(x),duration:Date.now()-o}}let b=vs(u);if(b)return{content:"",...K(b),duration:Date.now()-o};let w=$s(u);return{content:w.text,duration:Date.now()-o,claudeSessionId:w.sessionId,usage:w.usage,billedModel:w.billedModel}}catch(d){return console.error(`[runtime] execFile threw: ${d.message}`),{content:"",error:d.message||"Claude Code failed",duration:Date.now()-o}}}async function Ms(r,e,t,n,s,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=ae(r,e,n),d=hn(r,c,!0,s,e.model,e.systemPromptAppend);pt(e.agentId,r,e.model,s,"stream");let u="",l,g,m,b,w;try{let x=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),p=at(je(r.workspace)),f=Ge("claude",d,{cwd:r.workspace,timeout:x,reject:!1,env:p,extendEnv:!1,buffer:!1,stdin:"ignore"}),D=!1,C;if(i){let A=()=>{D=!0,C=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{f.kill("SIGTERM")}catch{}setTimeout(()=>{try{f.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?A():i.addEventListener("abort",A,{once:!0})}let T="",$=new ke("utf8");f.stdout&&f.stdout.on("data",A=>{T+=$.write(A);let R=T.split(`
|
|
11
|
+
`);T=R.pop()||"";for(let S of R)if(S.trim())try{let I=JSON.parse(S);if(o)try{o(I)}catch{}if(I.type==="assistant"&&I.message?.usage){let P=I.message.usage,E=(P.input_tokens||0)+(P.cache_read_input_tokens||0)+(P.cache_creation_input_tokens||0);E>0&&(b=E)}if(I.type==="assistant"&&I.message?.content){for(let P of I.message.content)if(P.type==="text"&&P.text){let E=P.text.slice(u.length);E&&(u=P.text,t(E,u))}}if(I.type==="content_block_delta"&&I.delta?.text&&(u+=I.delta.text,t(I.delta.text,u)),I.type==="result"&&I.result){if(I.is_error&&typeof I.result=="string")w=I.result;else{let P=(typeof I.result=="string",I.result);if(typeof P=="string"&&P.length>u.length){let E=P.slice(u.length);u=P,E&&t(E,u)}}I.usage&&(g={inputTokens:I.usage.input_tokens||0,outputTokens:I.usage.output_tokens||0,cacheReadTokens:I.usage.cache_read_input_tokens||0,cacheCreateTokens:I.usage.cache_creation_input_tokens||0}),typeof I.model=="string"&&(l=I.model),typeof I.session_id=="string"&&(m=I.session_id)}I.type==="system"&&I.subtype==="init"&&(typeof I.model=="string"&&(l=I.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${I.apiKeySource} version=${I.claude_code_version} model=${I.model} permMode=${I.permissionMode}
|
|
12
|
+
`))}catch{S.trim()&&!S.startsWith("{")&&(u+=S+`
|
|
13
|
+
`,t(S+`
|
|
14
|
+
`,u))}});let F=await f,k=$.end();if(k&&(T+=k),D)return{content:"",error:C||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&F.stdout&&(u=typeof F.stdout=="string"?F.stdout:""),F.exitCode!==0&&!u){let A=typeof F.stderr=="string"?F.stderr:"",R=F,S;return R.timedOut?S=`Claude Code timed out after ${Math.round(x/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:R.signal?S=A.trim()||`Claude Code killed by signal ${R.signal}`:R.code==="ENOENT"||/ENOENT|spawn claude/i.test((R.shortMessage||"")+" "+A)?S=fn():S=A.trim()||`Claude Code exited with code ${R.exitCode??"unknown"}`,{content:"",...K(S),duration:Date.now()-a}}return w?{content:"",...K(w),duration:Date.now()-a,usage:g,contextTokens:b,billedModel:l,claudeSessionId:m}:{content:u,duration:Date.now()-a,usage:g,contextTokens:b,billedModel:l,claudeSessionId:m}}catch(x){return{content:u||"",...K(x.message),duration:Date.now()-a,usage:g,contextTokens:b,billedModel:l,claudeSessionId:m}}}async function Rs(r,e,t,n){let s=Date.now(),o=ae(r,e,t),i=un(Ke(pn(),"agentx-codex-")),a=Ke(i,"last-message.txt"),c=yn(r,o,!1,e.model,e.systemPromptAppend,a,n);try{let d=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),u=await Ge("codex",c,{cwd:r.workspace,timeout:d,reject:!1,env:ut(r,e),extendEnv:!1,stdin:"ignore"}),l=Ss(u.stdout);if(u.exitCode!==0||l.apiError){let m=u,b;return m.timedOut?b=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:l.apiError?b=l.apiError:m.signal?b=u.stderr.trim()||`Codex CLI killed by signal ${m.signal}`:m.code==="ENOENT"||/ENOENT|spawn codex/i.test((m.shortMessage||"")+" "+u.stderr)?b=Be():b=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${m.exitCode??"unknown"}`,{content:"",...K(b),duration:Date.now()-s,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||n}}let g="";try{g=ln(a,"utf8").trim()}catch{}return g||(g=u.stdout.trim()),{content:g,duration:Date.now()-s,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||n}}catch(d){let u=/ENOENT|spawn codex/i.test(d?.message||"")?Be():d?.message;return{content:"",...K(u||"Codex CLI failed"),duration:Date.now()-s}}finally{gn(i,{recursive:!0,force:!0})}}async function Ps(r,e,t,n,s,o){let i=Date.now(),a=ae(r,e,n),c=un(Ke(pn(),"agentx-codex-")),d=Ke(c,"last-message.txt"),u=yn(r,a,!0,e.model,e.systemPromptAppend,d,s),l="",g,m,b,w;try{let x=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),p=Ge("codex",u,{cwd:r.workspace,timeout:x,reject:!1,env:ut(r,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||r.model,resumeSessionId:s})}catch{}let f="",D="",C=!1,T=new ke("utf8"),$=new ke("utf8"),F=Math.min(x,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),k,A=()=>{k&&clearTimeout(k),k=setTimeout(()=>{C=!0,p.kill("SIGTERM",{forceKillAfterTimeout:5e3})},F)};A(),p.stderr?.on("data",E=>{A(),D+=$.write(E),D.length>16e3&&(D=D.slice(-16e3))}),p.stdout?.on("data",E=>{A(),f+=T.write(E);let W=f.split(`
|
|
15
|
+
`);f=W.pop()||"";for(let _ of W)if(_.trim())try{let q=JSON.parse(_);if(o)try{o(q)}catch{}g=lt(q)||g,m=bn(q)||m,b=gt(q)||b,w=xn(q)||w;let O=Is(q);if(O&&O!==l){let J=O.startsWith(l)?O.slice(l.length):O;l=O.startsWith(l)?O:l+O,J&&t(J,l)}}catch{l+=_+`
|
|
13
16
|
`,t(_+`
|
|
14
|
-
`,
|
|
15
|
-
|
|
16
|
-
`,
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
`,u)}};x.stdout?.on("data",T=>{R+=S.write(T);let C=R.split(`
|
|
20
|
-
`)
|
|
21
|
-
|
|
22
|
-
${e.message}`:e.message,f=e.context?.sender,R=typeof f=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(f),$=e.context?.channel==="web-chat"&&R?{userId:f,agentId:e.agentId||"noqta-public"}:void 0,S=Kt(r),A=Object.keys(S).length>0,N={task:p,cwd:r.workspace,provider:w,model:e.model||r.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,noqtaContext:$,providerOpts:o,abortSignal:l.signal,mcpServers:A?S:void 0};if(s){let{generateStream:I}=await import("./agent-QGZIAZMY.js"),D="",F,W,O,q;for await(let P of I(N)){if(c)try{c(P)}catch{}if(P.type==="text_delta")D+=P.text,s(P.text,D);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==D){let J=P.result.content.slice(D.length);J?(D=P.result.content,s(J,D)):D=P.result.content}F=P.result.tokensUsed,P.result.inputTokens!=null&&(W=P.result.inputTokens),P.result.outputTokens!=null&&(O=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==D){let J=P.result.content.slice(D.length);J?(D=P.result.content,s(J,D)):D=P.result.content}P.result.tokensUsed!=null&&(F=P.result.tokensUsed)}else P.type==="error"&&(q=P.error)}return q&&!D?g?x():q==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${q}`),duration:Date.now()-d}:((W===void 0||O===void 0)&&F&&(W=Math.round(F*.7),O=F-W),{content:D||"Done.",tokensUsed:F,usage:W!==void 0||O!==void 0?{inputTokens:W||0,outputTokens:O||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:k}=await import("./agent-QGZIAZMY.js"),T=await k(N),C=T.inputTokens,_=T.outputTokens;if((C===void 0||_===void 0)&&T.tokensUsed){let I=T.tokensUsed;C=Math.round(I*.7),_=I-C}return{content:T.content||"Done.",tokensUsed:T.tokensUsed,usage:C!==void 0||_!==void 0?{inputTokens:C||0,outputTokens:_||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(w){return g?x():w?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${w.message}`),duration:Date.now()-d}}finally{clearTimeout(b),a&&a.removeEventListener("abort",m)}}async function Es(r,e,t,n,s,o){let i=We();if(!i)return null;let a=Date.now(),c=e.context?.channel||"api",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:c,chatId:d};if(e.freshSession)try{await i.kill(u,"freshSession=true")}catch{}let l,g=!1;try{let k=i.list().length;l=i.acquire(u,{agentId:e.agentId,channel:c,chatId:d,workspace:r.workspace,model:e.model||r.model,permissionMode:r.permissionMode,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),g=i.list().length>k}catch(k){return k instanceof pe,null}g&&pt(e.agentId,r,e.model,n,"persistent");let m=ae(r,e,t),b="",x,w,p,f,R,$,S=!1,A=()=>{S=!0,i.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?A():o.addEventListener("abort",A,{once:!0}));let N=!1;try{for await(let k of l.runTurn({message:m,taskId:e.taskId??"unknown"})){if(N=!0,s)try{s(k.raw)}catch{}if(k.type==="assistant"){let T=k.raw.message?.content??[];for(let _ of T)_.type==="text"&&typeof _.text=="string"&&(b=_.text);let C=k.raw.message?.usage;if(C){let _=(C.input_tokens||0)+(C.cache_read_input_tokens||0)+(C.cache_creation_input_tokens||0);_>0&&(f=_)}}if(k.type==="result"){let T=k.raw;if(T.is_error){let C=K(typeof T.result=="string"?T.result:"claude error");x=C.error,w=C.errorKind}else typeof T.result=="string"&&T.result.length>0&&(b=T.result);typeof T.session_id=="string"&&($=T.session_id),T.usage&&(p={inputTokens:T.usage.input_tokens||0,outputTokens:T.usage.output_tokens||0,cacheReadTokens:T.usage.cache_read_input_tokens||0,cacheCreateTokens:T.usage.cache_creation_input_tokens||0}),typeof T.message?.model=="string"?R=T.message.model:typeof T.model=="string"&&(R=T.model)}}}catch(k){if(S)x="task cancelled by operator",w="cancelled";else if(N){let T=K(`persistent claude process error: ${k?.message||String(k)}`);x=T.error,w=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${k?.message||k}); falling back to spawn-per-task`),i.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",A),null}finally{o&&o.removeEventListener("abort",A)}return S&&!x&&(x="task cancelled by operator",w="cancelled"),{content:S?"":b,error:x,errorKind:w,duration:Date.now()-a,usage:p,contextTokens:f,billedModel:R,claudeSessionId:$}}async function wn(r,e,t,n,s,o,i,a,c){switch(r.tier){case"claude-code":if(r.persistentProcess){let d=await Es(r,e,s,o,i,a);if(d!==null)return d}return n?Ms(r,e,n,s,o,i,a):As(r,e,s,o,a);case"codex-cli":return n?Ps(r,e,n,s,o,i):Rs(r,e,s,o);case"opencode":return Ds(r,e,n,s,o,i,a);case"sdk":{let d=r.provider||"claude",u=t[d]?.apiKey;return u?Os(r,e,u,s):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=r.provider||"claude-code",u=t[d],l=u?.apiKey;return _s(r,e,l,s,n,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${r.tier}`}}}import{readFileSync as fe,writeFileSync as Tn,mkdirSync as Ns,existsSync as ft,readdirSync as ht}from"fs";import{resolve as he}from"path";var mt=12e3,Ie=30,Fs=720,js=40,Ls=18e4,Hs="[Compacted conversation summary",Us=7*864e5,Ws=[/\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 Ks(r){return r?Ws.some(e=>e.test(r)):!1}var Bs=[{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 In(r){if(!r)return null;let e=0;for(let t of Bs)t.re.test(r)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function kn(r,e,t,n){if(r.length===0)return!1;let s=r[r.length-1];return s.role===e&&(s.name??"")===t&&s.content===n}function Gs(r){let e=r.slice(11,16),t=e.slice(0,2),n=parseInt(e.slice(3,5),10);if(Number.isNaN(n))return e;let s=Math.floor(n/15)*15;return`${t}:${s.toString().padStart(2,"0")}`}var qe=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=he(e,".agentx/sessions"),ft(this.sessionsDir)||Ns(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Fs),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??js),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Ls)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n){if(!this.adapterResolver)return;let s=this.sessionKey(e,t,n),o=this.seedingPromises.get(s);if(o)return o;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 d=await a.seedHistory(n,{maxMessages:Ie,maxChars:mt});d.length>0&&this.appendSeededMessages(i,d)}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 o of e.messages)o.externalId&&n.add(o.externalId);let s=0;for(let o of t)o.externalId&&n.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.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 he(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 o=this.sessionFile(s);if(ft(o))try{let d=JSON.parse(fe(o,"utf-8"));return this.cache.set(s,d),d}catch{}let i=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),c={id:s,agentId:e,channel:t,chatId:n,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(s,c),this.save(c),c}loadPreviousDaySession(e,t,n){let s=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${n}:${s}`,i=this.sessionFile(o);if(!ft(i))return null;try{return JSON.parse(fe(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,s,o){let i=this.getSession(e,t,n);kn(i.messages,"user",s,o)||(i.messages.push({role:"user",name:s,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,n,s){let o=this.getSession(e,t,n),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(s||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,n,s){let o=this.getSession(e,t,n);kn(o.messages,"agent",e,s)||(o.messages.push({role:"agent",name:e,content:s,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,s){let o=this.getSession(e,t,n);o.claudeSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}getCodexSessionId(e,t,n){return this.getSession(e,t,n).codexSessionId}setCodexSessionId(e,t,n,s){let o=this.getSession(e,t,n);o.codexSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,n){return this.getSession(e,t,n).opencodeSessionId}setOpenCodeSessionId(e,t,n,s){let o=this.getSession(e,t,n);o.opencodeSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,n,s={}){let o=this.getSession(e,t,n);if(o.messages.length===0)return"";let i=Math.max(1,s.maxMessages??Ie),a=Math.max(200,s.maxChars??mt),c=[],d=0;for(let g=o.messages.length-1;g>=0&&c.length<i;g--){let m=o.messages[g];if(d+=m.content.length,c.push(m),d>=a)break}c.reverse();let u=[`[Conversation history for today (${o.day})]`],l="";for(let g of c){let m=Gs(g.timestamp);m!==l&&(u.push(`\u2014 ${m} \u2014`),l=m);let b=g.name||(g.role==="user"?"User":"Agent");u.push(`${b}: ${g.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
|
|
23
|
-
`)}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(),o=e.after??s,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=ht(this.sessionsDir).filter($=>$.startsWith(`${a}:`)&&$.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=o.slice(0,10),u=i.slice(0,10),l=/:(\d{4}-\d{2}-\d{2})\.json$/,g=c.filter($=>{let S=$.match(l);if(!S)return!1;let A=S[1];return A>=d&&A<=u}),m=[],b=0,x=e.query?.toLowerCase(),w=e.participants?.length?new Set(e.participants):void 0;for(let $ of g){let S;try{S=JSON.parse(fe(he(this.sessionsDir,$),"utf-8"))}catch{continue}if(S.agentId===e.agentId&&!(e.channel&&S.channel!==e.channel)&&!(e.chatId&&S.chatId!==e.chatId))for(let A of S.messages)b++,!(!A.timestamp||A.timestamp<o||A.timestamp>=i)&&(w&&A.role==="user"&&!w.has(A.name??"")||x&&!A.content.toLowerCase().includes(x)||m.push({ts:A.timestamp,role:A.role,senderName:A.name??"",content:A.content,channel:S.channel,chatId:S.chatId,day:S.day,sessionFile:$}))}m.sort(($,S)=>S.ts.localeCompare($.ts));let p=m.slice(0,t),f=p.length>0?p[p.length-1].ts:null,R=m.length>t;return{turns:p,oldestTs:f,hasMore:R,totalScanned:b}}recentByChatId(e){let t=Math.min(Math.max(e.limit??Ie,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),s=n.slice(0,10),o;try{o=ht(this.sessionsDir).filter(l=>l.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`,a=o.filter(l=>{if(!l.includes(i))return!1;let g=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=s:!1}),c=[];for(let l of a){let g;try{g=JSON.parse(fe(he(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let m of g.messages)!m.timestamp||m.timestamp<n||c.push({ts:m.timestamp,role:m.role,senderName:m.name??"",content:m.content,agentId:g.agentId,sessionFile:l})}let d=new Set,u=[];for(let l of c){let g=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;d.has(g)||(d.add(g),u.push(l))}return u.sort((l,g)=>l.ts.localeCompare(g.ts)),u.slice(-t)}isSessionStale(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:Date.now()-new Date(s.updatedAt).getTime()>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,n,s){if(s!==void 0&&s!==""&&!Ks(s))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=ht(this.sessionsDir).filter(d=>d.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&d.includes(o)&&d.endsWith(".json")),c=[];for(let d of a)try{let u=JSON.parse(fe(he(this.sessionsDir,d),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),m=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,b=l.map(x=>` [${x.timestamp.slice(11,16)}] ${x.name||x.role}: ${x.content.slice(0,200)}`);c.push(`From ${m} (${u.channel}):
|
|
17
|
+
`,l)}});let R=await p;k&&clearTimeout(k);let S=T.end();S&&(f+=S);let I=$.end();if(I&&(D+=I),R.exitCode!==0&&!l||w){let E=D||(typeof R.stderr=="string"?R.stderr:""),W=R,_;return C?_=`Codex CLI produced no output for ${Math.round(F/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:W.timedOut?_=`Codex CLI timed out after ${Math.round(x/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:w?_=w:W.signal?_=E.trim()||`Codex CLI killed by signal ${W.signal}`:W.code==="ENOENT"||/ENOENT|spawn codex/i.test((W.shortMessage||"")+" "+E)?_=Be():_=E.trim()||`Codex CLI exited with code ${W.exitCode??"unknown"}`,{content:"",...K(_),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:b||s}}let P="";try{P=ln(d,"utf8").trim()}catch{}if(P&&P!==l){let E=P.startsWith(l)?P.slice(l.length):P;l=P,E&&t(E,l)}return{content:l,duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:b||s}}catch(x){let p=/ENOENT|spawn codex/i.test(x?.message||"")?Be():x?.message;return{content:l,...K(p||"Codex CLI failed"),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:b||s}}finally{gn(c,{recursive:!0,force:!0})}}async function Ds(r,e,t,n,s,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let d=ae(r,e,n),u=xs(r,d,e.model,e.systemPromptAppend,s),l="",g,m=s,b;try{let w=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),x=Ge("opencode",u,{cwd:r.workspace,timeout:w,reject:!1,env:ks(r,e),extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||r.model,resumeSessionId:s})}catch{}let p=!1,f,D=()=>{p=!0,f=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{x.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",D,{once:!0});let C="",T="",$=new ke("utf8"),F=new ke("utf8"),k=R=>{if(R.trim())try{let S=JSON.parse(R);try{o?.(S)}catch{}typeof S.sessionID=="string"&&(m=S.sessionID);let I=S.type==="text"&&typeof S.part?.text=="string"?S.part.text:void 0;I&&(l+=I,t?.(I,l));let P=S.type==="reasoning"&&typeof S.part?.text=="string"?S.part.text:void 0;P&&a?.(P);let E=S.type==="step_finish"?S.part?.tokens:void 0;E&&(g={inputTokens:ee(E.input),outputTokens:ee(E.output),cacheReadTokens:ee(E.cache?.read),cacheCreateTokens:ee(E.cache?.write)}),b=ws(S)||b}catch{l+=R+`
|
|
18
|
+
`,t?.(R+`
|
|
19
|
+
`,l)}};x.stdout?.on("data",R=>{C+=$.write(R);let S=C.split(`
|
|
20
|
+
`);C=S.pop()||"";for(let I of S)k(I)}),x.stderr?.on("data",R=>{T+=F.write(R)});let A=await x;if(i&&i.removeEventListener("abort",D),C+=$.end(),C.trim()&&k(C),T+=F.end(),p)return{content:"",error:f||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:m};if(A.exitCode!==0||b){let R=A,S;return R.timedOut?S=`OpenCode timed out after ${Math.round(w/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:b?S=b:R.code==="ENOENT"||/ENOENT|spawn opencode/i.test((R.shortMessage||"")+" "+T)?S=an():S=T.trim()||`OpenCode exited with code ${R.exitCode??"unknown"}`,{content:"",...K(S),duration:Date.now()-c,usage:g,opencodeSessionId:m}}return{content:l.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||r.model,opencodeSessionId:m}}catch(w){let x=/ENOENT|spawn opencode/i.test(w?.message||"")?an():w?.message;return{content:l,...K(x||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:m}}}async function Os(r,e,t,n){let s=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ae(r,e,n),c="",d=i({prompt:a,options:{model:e.model||r.model,cwd:r.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-s}}catch(o){return{content:"",...K(`SDK error: ${o.message}`),duration:Date.now()-s}}}async function _s(r,e,t,n,s,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),l=new AbortController,g=!1,m=()=>{let x=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(x))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let b=setTimeout(()=>{g=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);b.unref?.();let w=()=>({content:"",...K(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let x=r.provider||"claude-code",p=n?`${n}
|
|
21
|
+
|
|
22
|
+
${e.message}`:e.message,f=e.context?.sender,D=typeof f=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(f),C=e.context?.channel==="web-chat"&&D?{userId:f,agentId:e.agentId||"noqta-public"}:void 0,T=Kt(r),$=Object.keys(T).length>0,F={task:p,cwd:r.workspace,provider:x,model:e.model||r.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,noqtaContext:C,providerOpts:o,abortSignal:l.signal,mcpServers:$?T:void 0};if(s){let{generateStream:I}=await import("./agent-5QMITZT6.js"),P="",E,W,_,q;for await(let O of I(F)){if(c)try{c(O)}catch{}if(O.type==="text_delta")P+=O.text,s(O.text,P);else if(O.type==="thinking_delta")O.text&&i&&i(O.text);else if(O.type==="generate_result"){if(O.result.content&&O.result.content!==P){let J=O.result.content.slice(P.length);J?(P=O.result.content,s(J,P)):P=O.result.content}E=O.result.tokensUsed,O.result.inputTokens!=null&&(W=O.result.inputTokens),O.result.outputTokens!=null&&(_=O.result.outputTokens)}else if(O.type==="done"){if(O.result.content&&O.result.content!==P){let J=O.result.content.slice(P.length);J?(P=O.result.content,s(J,P)):P=O.result.content}O.result.tokensUsed!=null&&(E=O.result.tokensUsed)}else O.type==="error"&&(q=O.error)}return q&&!P?g?w():q==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${q}`),duration:Date.now()-d}:((W===void 0||_===void 0)&&E&&(W=Math.round(E*.7),_=E-W),{content:P||"Done.",tokensUsed:E,usage:W!==void 0||_!==void 0?{inputTokens:W||0,outputTokens:_||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:k}=await import("./agent-5QMITZT6.js"),A=await k(F),R=A.inputTokens,S=A.outputTokens;if((R===void 0||S===void 0)&&A.tokensUsed){let I=A.tokensUsed;R=Math.round(I*.7),S=I-R}return{content:A.content||"Done.",tokensUsed:A.tokensUsed,usage:R!==void 0||S!==void 0?{inputTokens:R||0,outputTokens:S||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(x){return g?w():x?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${x.message}`),duration:Date.now()-d}}finally{clearTimeout(b),a&&a.removeEventListener("abort",m)}}async function Es(r,e,t,n,s,o){let i=We();if(!i)return null;let a=Date.now(),c=e.context?.channel||"api",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:c,chatId:d};if(e.freshSession)try{await i.kill(u,"freshSession=true")}catch{}let l,g=!1;try{let k=i.list().length;l=i.acquire(u,{agentId:e.agentId,channel:c,chatId:d,workspace:r.workspace,model:e.model||r.model,permissionMode:r.permissionMode,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),g=i.list().length>k}catch(k){return k instanceof pe,null}g&&pt(e.agentId,r,e.model,n,"persistent");let m=ae(r,e,t),b="",w,x,p,f,D,C,T=!1,$=()=>{T=!0,i.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?$():o.addEventListener("abort",$,{once:!0}));let F=!1;try{for await(let k of l.runTurn({message:m,taskId:e.taskId??"unknown"})){if(F=!0,s)try{s(k.raw)}catch{}if(k.type==="assistant"){let A=k.raw.message?.content??[];for(let S of A)S.type==="text"&&typeof S.text=="string"&&(b=S.text);let R=k.raw.message?.usage;if(R){let S=(R.input_tokens||0)+(R.cache_read_input_tokens||0)+(R.cache_creation_input_tokens||0);S>0&&(f=S)}}if(k.type==="result"){let A=k.raw;if(A.is_error){let R=K(typeof A.result=="string"?A.result:"claude error");w=R.error,x=R.errorKind}else typeof A.result=="string"&&A.result.length>0&&(b=A.result);typeof A.session_id=="string"&&(C=A.session_id),A.usage&&(p={inputTokens:A.usage.input_tokens||0,outputTokens:A.usage.output_tokens||0,cacheReadTokens:A.usage.cache_read_input_tokens||0,cacheCreateTokens:A.usage.cache_creation_input_tokens||0}),typeof A.message?.model=="string"?D=A.message.model:typeof A.model=="string"&&(D=A.model)}}}catch(k){if(T)w="task cancelled by operator",x="cancelled";else if(F){let A=K(`persistent claude process error: ${k?.message||String(k)}`);w=A.error,x=A.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${k?.message||k}); falling back to spawn-per-task`),i.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",$),null}finally{o&&o.removeEventListener("abort",$)}return T&&!w&&(w="task cancelled by operator",x="cancelled"),{content:T?"":b,error:w,errorKind:x,duration:Date.now()-a,usage:p,contextTokens:f,billedModel:D,claudeSessionId:C}}async function wn(r,e,t,n,s,o,i,a,c){switch(r.tier){case"claude-code":if(r.persistentProcess){let d=await Es(r,e,s,o,i,a);if(d!==null)return d}return n?Ms(r,e,n,s,o,i,a):As(r,e,s,o,a);case"codex-cli":return n?Ps(r,e,n,s,o,i):Rs(r,e,s,o);case"opencode":return Ds(r,e,n,s,o,i,a,c);case"sdk":{let d=r.provider||"claude",u=t[d]?.apiKey;return u?Os(r,e,u,s):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=r.provider||"claude-code",u=t[d],l=u?.apiKey;return _s(r,e,l,s,n,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${r.tier}`}}}import{readFileSync as fe,writeFileSync as Tn,mkdirSync as Ns,existsSync as ft,readdirSync as ht}from"fs";import{resolve as he}from"path";var mt=12e3,Ie=30,Fs=720,js=40,Ls=18e4,Hs="[Compacted conversation summary",Us=7*864e5,Ws=[/\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 Ks(r){return r?Ws.some(e=>e.test(r)):!1}var Bs=[{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 In(r){if(!r)return null;let e=0;for(let t of Bs)t.re.test(r)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function kn(r,e,t,n){if(r.length===0)return!1;let s=r[r.length-1];return s.role===e&&(s.name??"")===t&&s.content===n}function Gs(r){let e=r.slice(11,16),t=e.slice(0,2),n=parseInt(e.slice(3,5),10);if(Number.isNaN(n))return e;let s=Math.floor(n/15)*15;return`${t}:${s.toString().padStart(2,"0")}`}var qe=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=he(e,".agentx/sessions"),ft(this.sessionsDir)||Ns(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Fs),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??js),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Ls)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n){if(!this.adapterResolver)return;let s=this.sessionKey(e,t,n),o=this.seedingPromises.get(s);if(o)return o;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 d=await a.seedHistory(n,{maxMessages:Ie,maxChars:mt});d.length>0&&this.appendSeededMessages(i,d)}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 o of e.messages)o.externalId&&n.add(o.externalId);let s=0;for(let o of t)o.externalId&&n.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.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 he(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 o=this.sessionFile(s);if(ft(o))try{let d=JSON.parse(fe(o,"utf-8"));return this.cache.set(s,d),d}catch{}let i=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),c={id:s,agentId:e,channel:t,chatId:n,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(s,c),this.save(c),c}loadPreviousDaySession(e,t,n){let s=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${n}:${s}`,i=this.sessionFile(o);if(!ft(i))return null;try{return JSON.parse(fe(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,s,o){let i=this.getSession(e,t,n);kn(i.messages,"user",s,o)||(i.messages.push({role:"user",name:s,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,n,s){let o=this.getSession(e,t,n),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(s||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,n,s){let o=this.getSession(e,t,n);kn(o.messages,"agent",e,s)||(o.messages.push({role:"agent",name:e,content:s,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,s){let o=this.getSession(e,t,n);o.claudeSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}getCodexSessionId(e,t,n){return this.getSession(e,t,n).codexSessionId}setCodexSessionId(e,t,n,s){let o=this.getSession(e,t,n);o.codexSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,n){return this.getSession(e,t,n).opencodeSessionId}setOpenCodeSessionId(e,t,n,s){let o=this.getSession(e,t,n);o.opencodeSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,n,s={}){let o=this.getSession(e,t,n);if(o.messages.length===0)return"";let i=Math.max(1,s.maxMessages??Ie),a=Math.max(200,s.maxChars??mt),c=[],d=0;for(let g=o.messages.length-1;g>=0&&c.length<i;g--){let m=o.messages[g];if(d+=m.content.length,c.push(m),d>=a)break}c.reverse();let u=[`[Conversation history for today (${o.day})]`],l="";for(let g of c){let m=Gs(g.timestamp);m!==l&&(u.push(`\u2014 ${m} \u2014`),l=m);let b=g.name||(g.role==="user"?"User":"Agent");u.push(`${b}: ${g.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
|
|
23
|
+
`)}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(),o=e.after??s,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=ht(this.sessionsDir).filter(C=>C.startsWith(`${a}:`)&&C.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=o.slice(0,10),u=i.slice(0,10),l=/:(\d{4}-\d{2}-\d{2})\.json$/,g=c.filter(C=>{let T=C.match(l);if(!T)return!1;let $=T[1];return $>=d&&$<=u}),m=[],b=0,w=e.query?.toLowerCase(),x=e.participants?.length?new Set(e.participants):void 0;for(let C of g){let T;try{T=JSON.parse(fe(he(this.sessionsDir,C),"utf-8"))}catch{continue}if(T.agentId===e.agentId&&!(e.channel&&T.channel!==e.channel)&&!(e.chatId&&T.chatId!==e.chatId))for(let $ of T.messages)b++,!(!$.timestamp||$.timestamp<o||$.timestamp>=i)&&(x&&$.role==="user"&&!x.has($.name??"")||w&&!$.content.toLowerCase().includes(w)||m.push({ts:$.timestamp,role:$.role,senderName:$.name??"",content:$.content,channel:T.channel,chatId:T.chatId,day:T.day,sessionFile:C}))}m.sort((C,T)=>T.ts.localeCompare(C.ts));let p=m.slice(0,t),f=p.length>0?p[p.length-1].ts:null,D=m.length>t;return{turns:p,oldestTs:f,hasMore:D,totalScanned:b}}recentByChatId(e){let t=Math.min(Math.max(e.limit??Ie,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),s=n.slice(0,10),o;try{o=ht(this.sessionsDir).filter(l=>l.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`,a=o.filter(l=>{if(!l.includes(i))return!1;let g=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=s:!1}),c=[];for(let l of a){let g;try{g=JSON.parse(fe(he(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let m of g.messages)!m.timestamp||m.timestamp<n||c.push({ts:m.timestamp,role:m.role,senderName:m.name??"",content:m.content,agentId:g.agentId,sessionFile:l})}let d=new Set,u=[];for(let l of c){let g=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;d.has(g)||(d.add(g),u.push(l))}return u.sort((l,g)=>l.ts.localeCompare(g.ts)),u.slice(-t)}isSessionStale(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:Date.now()-new Date(s.updatedAt).getTime()>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,n,s){if(s!==void 0&&s!==""&&!Ks(s))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=ht(this.sessionsDir).filter(d=>d.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&d.includes(o)&&d.endsWith(".json")),c=[];for(let d of a)try{let u=JSON.parse(fe(he(this.sessionsDir,d),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),m=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,b=l.map(w=>` [${w.timestamp.slice(11,16)}] ${w.name||w.role}: ${w.content.slice(0,200)}`);c.push(`From ${m} (${u.channel}):
|
|
24
24
|
${b.join(`
|
|
25
25
|
`)}`)}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(`
|
|
26
|
-
`)}catch{return""}}async compactIfNeeded(e,t,n,s){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-NWEMOSHA.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,s);return d.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,d),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:d.qualityScore,lostEntities:d.lostEntities,drift:d.drift})}hasCompaction(e,t,n){let s=this.getSession(e,t,n);return s.messages.length>0&&s.messages[0].content.startsWith(Hs)}clearClaudeSessionId(e,t,n){let s=this.getSession(e,t,n);delete s.claudeSessionId,delete s.codexSessionId,delete s.opencodeSessionId,delete s.turnCount,delete s.lastTurnInputTokens,delete s.lastTurnContextTokens,s.updatedAt=new Date().toISOString(),this.save(s)}clearSession(e,t,n){let s=this.getSession(e,t,n);s.messages=[],delete s.claudeSessionId,delete s.codexSessionId,delete s.opencodeSessionId,delete s.turnCount,delete s.lastTurnInputTokens,delete s.lastTurnContextTokens,s.updatedAt=new Date().toISOString(),this.save(s)}shouldRotateByTurns(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:(s.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:(s.lastTurnContextTokens??s.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens}recordTurnUsage(e,t,n,s,o){let i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(s.inputTokens||0)+(s.cacheReadTokens||0)+(s.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return he(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(fe(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,s,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:s,reason:o,capturedAt:new Date().toISOString()},Tn(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,n){let s=this.readRotationMemos()[`${e}:${t}:${n}`];if(!s?.memo)return null;let o=Date.now()-Date.parse(s.capturedAt);return!Number.isFinite(o)||o>Us?null:s}getTurnCount(e,t,n){return this.getSession(e,t,n).turnCount??0}getLastTurnInputTokens(e,t,n){return this.getSession(e,t,n).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,n){let s=this.getSession(e,t,n);return s.lastTurnContextTokens??s.lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>Ie&&(e.messages=e.messages.slice(-Ie));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>mt&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let s=t-e.messages.length;s>0&&ie.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);Tn(t,JSON.stringify(e,null,2))}catch{}}};var Je=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,o=n.filter(c=>c>s),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],d=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:d}}if(o.length>=this.maxPerHour){let c=o[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:d}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,s=Date.now()+n,o=!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)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=s-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,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 Se,writeFileSync as Sn,appendFileSync as qs,existsSync as me,mkdirSync as Js}from"fs";import{resolve as ye}from"path";var vn={"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}},$n=2e5,zs=1.5;function Qs(r){let e=r.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 An(r){return r.inputTokens+r.cacheReadTokens+r.cacheCreateTokens>$n?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:r.inputTokens,tier2OutputTokens:r.outputTokens,tier2CacheReadTokens:r.cacheReadTokens,tier2CacheCreateTokens:r.cacheCreateTokens}:{inputTokens:r.inputTokens,outputTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens,cacheCreateTokens:r.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var Cn=500,Xs=".agentx/pricing/custom.json",be=class{dir;cache=null;pricing;constructor(e=ye(process.cwd(),".agentx/usage")){this.dir=e,Js(this.dir,{recursive:!0}),this.pricing=Ys()}getPricing(){return this.pricing}static calculateCost(e,t,n=vn){let s=Qs(t||e.model||"claude-sonnet"),o=n[s]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,d=e.tier2CacheCreateTokens||0,u=(e.inputTokens||0)/1e6*o.input+(e.outputTokens||0)/1e6*o.output+(e.cacheReadTokens||0)/1e6*o.cacheRead+(e.cacheCreateTokens||0)/1e6*o.cacheCreate,l=i/1e6*o.input+a/1e6*o.output+c/1e6*o.cacheRead+d/1e6*o.cacheCreate;return u+l*zs}cost(e,t){return be.calculateCost(e,t,this.pricing)}record(e,t,n,s,o,i,a,c,d){let u=this.today(),l=u.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:[]};l.tasks++,l.totalDuration+=t,a&&(l.model=a);let g=0,m=0,b=0,
|
|
26
|
+
`)}catch{return""}}async compactIfNeeded(e,t,n,s){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-NWEMOSHA.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,s);return d.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,d),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:d.qualityScore,lostEntities:d.lostEntities,drift:d.drift})}hasCompaction(e,t,n){let s=this.getSession(e,t,n);return s.messages.length>0&&s.messages[0].content.startsWith(Hs)}clearClaudeSessionId(e,t,n){let s=this.getSession(e,t,n);delete s.claudeSessionId,delete s.codexSessionId,delete s.opencodeSessionId,delete s.turnCount,delete s.lastTurnInputTokens,delete s.lastTurnContextTokens,s.updatedAt=new Date().toISOString(),this.save(s)}clearSession(e,t,n){let s=this.getSession(e,t,n);s.messages=[],delete s.claudeSessionId,delete s.codexSessionId,delete s.opencodeSessionId,delete s.turnCount,delete s.lastTurnInputTokens,delete s.lastTurnContextTokens,s.updatedAt=new Date().toISOString(),this.save(s)}shouldRotateByTurns(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:(s.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:(s.lastTurnContextTokens??s.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens}recordTurnUsage(e,t,n,s,o){let i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(s.inputTokens||0)+(s.cacheReadTokens||0)+(s.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return he(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(fe(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,s,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:s,reason:o,capturedAt:new Date().toISOString()},Tn(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,n){let s=this.readRotationMemos()[`${e}:${t}:${n}`];if(!s?.memo)return null;let o=Date.now()-Date.parse(s.capturedAt);return!Number.isFinite(o)||o>Us?null:s}getTurnCount(e,t,n){return this.getSession(e,t,n).turnCount??0}getLastTurnInputTokens(e,t,n){return this.getSession(e,t,n).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,n){let s=this.getSession(e,t,n);return s.lastTurnContextTokens??s.lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>Ie&&(e.messages=e.messages.slice(-Ie));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>mt&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let s=t-e.messages.length;s>0&&ie.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);Tn(t,JSON.stringify(e,null,2))}catch{}}};var Je=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,o=n.filter(c=>c>s),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],d=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:d}}if(o.length>=this.maxPerHour){let c=o[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:d}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,s=Date.now()+n,o=!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)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=s-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,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 Se,writeFileSync as Sn,appendFileSync as qs,existsSync as me,mkdirSync as Js}from"fs";import{resolve as ye}from"path";var vn={"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}},$n=2e5,zs=1.5;function Qs(r){let e=r.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 An(r){return r.inputTokens+r.cacheReadTokens+r.cacheCreateTokens>$n?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:r.inputTokens,tier2OutputTokens:r.outputTokens,tier2CacheReadTokens:r.cacheReadTokens,tier2CacheCreateTokens:r.cacheCreateTokens}:{inputTokens:r.inputTokens,outputTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens,cacheCreateTokens:r.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var Cn=500,Xs=".agentx/pricing/custom.json",be=class{dir;cache=null;pricing;constructor(e=ye(process.cwd(),".agentx/usage")){this.dir=e,Js(this.dir,{recursive:!0}),this.pricing=Ys()}getPricing(){return this.pricing}static calculateCost(e,t,n=vn){let s=Qs(t||e.model||"claude-sonnet"),o=n[s]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,d=e.tier2CacheCreateTokens||0,u=(e.inputTokens||0)/1e6*o.input+(e.outputTokens||0)/1e6*o.output+(e.cacheReadTokens||0)/1e6*o.cacheRead+(e.cacheCreateTokens||0)/1e6*o.cacheCreate,l=i/1e6*o.input+a/1e6*o.output+c/1e6*o.cacheRead+d/1e6*o.cacheCreate;return u+l*zs}cost(e,t){return be.calculateCost(e,t,this.pricing)}record(e,t,n,s,o,i,a,c,d){let u=this.today(),l=u.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:[]};l.tasks++,l.totalDuration+=t,a&&(l.model=a);let g=0,m=0,b=0,w=0,x=0,p=0,f=0,D=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>$n?(x=n.inputTokens,p=n.outputTokens,f=n.cacheReadTokens,D=n.cacheCreateTokens):(g=n.inputTokens,m=n.outputTokens,b=n.cacheReadTokens,w=n.cacheCreateTokens):s!==void 0&&o!==void 0&&(g=Math.ceil(s/4),m=Math.ceil(o/4)),l.inputTokens+=g,l.outputTokens+=m,l.cacheReadTokens+=b,l.cacheCreateTokens+=w,l.tier2InputTokens=(l.tier2InputTokens||0)+x,l.tier2OutputTokens=(l.tier2OutputTokens||0)+p,l.tier2CacheReadTokens=(l.tier2CacheReadTokens||0)+f,l.tier2CacheCreateTokens=(l.tier2CacheCreateTokens||0)+D,i&&l.errors++,l.byChannel||(l.byChannel={});let C=(c||"other").toLowerCase(),T=l.byChannel[C]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};T.tasks++,T.totalDuration+=t,T.inputTokens+=g,T.outputTokens+=m,T.cacheReadTokens+=b,T.cacheCreateTokens+=w,T.tier2InputTokens+=x,T.tier2OutputTokens+=p,T.tier2CacheReadTokens+=f,T.tier2CacheCreateTokens+=D,i&&T.errors++,l.byChannel[C]=T,d&&(l.sessionKeys||(l.sessionKeys=[]),l.sessionKeys.includes(d)||(l.sessionKeys.push(d),l.sessionKeys.length>Cn&&l.sessionKeys.splice(0,l.sessionKeys.length-Cn))),u.agents[e]=l,this.save(u)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(me(t))try{return this.cache=JSON.parse(Se(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!me(t))return null;try{return JSON.parse(Se(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,o=0,i=0,a=0,c=0,d=0,u="",l=0,g={},m={},b={};for(let[w,x]of Object.entries(n.agents)){let p=this.cost(x);g[w]=p,s+=x.tasks,o+=(x.inputTokens||0)+(x.tier2InputTokens||0),i+=(x.outputTokens||0)+(x.tier2OutputTokens||0),a+=(x.cacheReadTokens||0)+(x.tier2CacheReadTokens||0),c+=(x.cacheCreateTokens||0)+(x.tier2CacheCreateTokens||0),d+=p,p>l&&(l=p,u=w);let f=x.sessionKeys?.length||0;m[w]={sessions:f,avgTasksPerSession:f>0?x.tasks/f:x.tasks};for(let[D,C]of Object.entries(x.byChannel||{})){let T=this.cost(C,x.model);b[D]=(b[D]||0)+T}}return{date:t,totalTasks:s,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:u,topCost:l,agentCosts:g,agentSessionStats:m,byChannel:b}}appendToTokenCosts(e,t){let n=t||ye(process.cwd(),".agentx/TOKEN_COSTS.md"),s=d=>d<.01?d.toFixed(4):d.toFixed(2),o=d=>d>=1e6?`${(d/1e6).toFixed(1)}M`:d>=1e3?`${(d/1e3).toFixed(0)}K`:String(d),i=Object.entries(e.agentCosts).sort(([,d],[,u])=>u-d).map(([d,u])=>{let l=e.agentSessionStats[d],g=l&&l.sessions>0?` (${l.sessions}s, ${l.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${d}: $${s(u)}${g}`}).join(", "),a=Object.entries(e.byChannel).sort(([,d],[,u])=>u-d).map(([d,u])=>`${d}: $${s(u)}`).join(", "),c=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${s(e.totalCost)} | ${i} | ${a} |`;me(n)?qs(n,c+`
|
|
27
27
|
`):Sn(n,`# Token Costs
|
|
28
28
|
|
|
29
29
|
Daily token cost tracking. Auto-appended at midnight (Africa/Tunis).
|
|
@@ -32,7 +32,7 @@ Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
|
32
32
|
| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
|
|
33
33
|
|------|-------|-------|--------|---------|---------|------|-----------|-------------|
|
|
34
34
|
`+c+`
|
|
35
|
-
`)}hasTokenCostsEntry(e,t){let n=t||ye(process.cwd(),".agentx/TOKEN_COSTS.md");if(!me(n))return!1;try{let s=Se(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(s)}catch{return!1}}lastTokenCostsDate(e){let t=e||ye(process.cwd(),".agentx/TOKEN_COSTS.md");if(!me(t))return null;try{let s=Se(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(s.length===0)return null;let o=s.map(i=>i.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(i=>!!i);return o.sort(),o[o.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,s=[],o=this.lastTokenCostsDate(t.filePath),i=[],a=new Date(`${e}T00:00:00Z`);for(let c=0;c<n;c++){let d=a.toISOString().slice(0,10);if(o&&d<=o)break;i.push(d),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let c of i){if(this.hasTokenCostsEntry(c,t.filePath))continue;let d=this.generateDailyReport(c);!d||d.totalTasks===0||(this.appendToTokenCosts(d,t.filePath),s.push(c))}return s}summary(e=7){let t=0,n=0,s=0,o=0,i=0,a=0,c=0,d={},u={};for(let b=0;b<e;b++){let
|
|
35
|
+
`)}hasTokenCostsEntry(e,t){let n=t||ye(process.cwd(),".agentx/TOKEN_COSTS.md");if(!me(n))return!1;try{let s=Se(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(s)}catch{return!1}}lastTokenCostsDate(e){let t=e||ye(process.cwd(),".agentx/TOKEN_COSTS.md");if(!me(t))return null;try{let s=Se(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(s.length===0)return null;let o=s.map(i=>i.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(i=>!!i);return o.sort(),o[o.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,s=[],o=this.lastTokenCostsDate(t.filePath),i=[],a=new Date(`${e}T00:00:00Z`);for(let c=0;c<n;c++){let d=a.toISOString().slice(0,10);if(o&&d<=o)break;i.push(d),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let c of i){if(this.hasTokenCostsEntry(c,t.filePath))continue;let d=this.generateDailyReport(c);!d||d.totalTasks===0||(this.appendToTokenCosts(d,t.filePath),s.push(c))}return s}summary(e=7){let t=0,n=0,s=0,o=0,i=0,a=0,c=0,d={},u={};for(let b=0;b<e;b++){let w=new Date(Date.now()-b*864e5).toISOString().slice(0,10),x=this.getDate(w);if(x)for(let[p,f]of Object.entries(x.agents)){let D=this.cost(f);t+=f.tasks;let C=(f.inputTokens||0)+(f.tier2InputTokens||0),T=(f.outputTokens||0)+(f.tier2OutputTokens||0),$=(f.cacheReadTokens||0)+(f.tier2CacheReadTokens||0),F=(f.cacheCreateTokens||0)+(f.tier2CacheCreateTokens||0);n+=C,s+=T,o+=$,i+=F,a+=f.errors,c+=D;let k=d[p]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};k.tasks+=f.tasks,k.input+=C,k.output+=T,k.cacheRead+=$,k.cacheCreate+=F,k.total=k.input+k.output+k.cacheRead+k.cacheCreate,k.totalDuration+=f.totalDuration,k.avgDuration=k.totalDuration/k.tasks,k.cost+=D,k.sessions+=f.sessionKeys?.length||0,f.model&&(k.model=f.model),d[p]=k;for(let[A,R]of Object.entries(f.byChannel||{})){let S=this.cost(R,f.model),I=u[A]||{tasks:0,cost:0};I.tasks+=R.tasks,I.cost+=S,u[A]=I}}}let l=n+s+o+i,g=o+i>0?o/(o+i):0,m={};for(let[b,w]of Object.entries(d))m[b]={sessions:w.sessions,avgTasksPerSession:w.sessions>0?w.tasks/w.sessions:w.tasks};return{totalTasks:t,totalTokens:l,totalInput:n,totalOutput:s,totalCacheRead:o,totalCacheCreate:i,cacheHitRatio:g,totalErrors:a,totalCost:c,byAgent:d,byChannel:u,sessionStats:m}}filePath(e){return ye(this.dir,`${e}.json`)}save(e){try{Sn(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function Ys(){let r=JSON.parse(JSON.stringify(vn));try{let e=ye(process.cwd(),Xs);if(!me(e))return r;let t=JSON.parse(Se(e,"utf-8"));for(let[n,s]of Object.entries(t))r[n]||(r[n]={input:0,output:0,cacheRead:0,cacheCreate:0}),Object.assign(r[n],s)}catch{}return r}var Zs={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:600,memory:600,history:1200,"cross-chat":800,wiki:1e3}},Mn=4;function Rn(r,e=Zs){let t=Vs(r,e);t.sort((i,a)=>i.priority-a.priority);let n=[],s=0,o=e.totalBudget*Mn;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Mn,c=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(s+c.length>o){let d=o-s;d>100&&n.push(c.slice(0,d)+"...");break}n.push(c),s+=c.length}return n.join(`
|
|
36
36
|
|
|
37
37
|
`)}function Vs(r,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(er(r,t("channel",200))),n.push(tr(r,t("scope",200))),r.landscape&&n.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:r.landscape,tags:["landscape","world-model"]}),r.systemPrompt&&n.push({name:"identity",priority:4,maxTokens:t("identity",200),content:r.systemPrompt.split(`
|
|
38
38
|
`)[0],tags:["identity",r.agentId]}),r.bootstrapContext&&n.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:r.bootstrapContext,tags:["bootstrap","identity","personality"]}),r.references&&n.push({name:"references",priority:4.7,maxTokens:t("references",500),content:r.references,tags:["references","verified","deterministic"]}),r.intent&&r.intent.path.length>0){let i=[`[Intent path: ${r.intent.pathLabel}${r.intent.status==="pending"?" (pending approval)":""}]`],a=r.intent.path[r.intent.path.length-1],c=r.intent.axes?.[a];if(c&&Object.keys(c).length){let d=Object.entries(c).map(([u,l])=>` ${u}: ${l}`).join(`
|
|
@@ -44,7 +44,7 @@ Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
|
44
44
|
`),tags:s,rules:n}}function tr(r,e){let t=[],n=[];if(r.channelScope==="group"&&r.groupName?(t.push(`Group: ${r.groupName}`),n.push("group",r.groupName)):r.channelScope==="project"&&r.projectPath?(t.push(`Project: ${r.projectPath}`),n.push("project",r.projectPath)):r.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),r.channelMeta){let s=r.channelMeta;if(s.agents?.length&&(t.push(`[Verified bots in this chat: ${s.agents.map(o=>o.handle||o.name||o.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 o of s.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
45
45
|
`),tags:n}}function nr(r){let e=[],t=r.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}import{readFileSync as sr,writeFileSync as Pn,appendFileSync as rr,mkdirSync as or,existsSync as Dn}from"fs";import{resolve as yt}from"path";var On=200,ir=7,ze=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=yt(e,".agentx/memory"),Dn(this.memoryDir)||or(this.memoryDir,{recursive:!0})}filePath(e){return yt(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()};rr(this.filePath(e),JSON.stringify(n)+`
|
|
46
46
|
`)}getAll(e){let t=this.filePath(e);if(!Dn(t))return[];try{return sr(t,"utf-8").split(`
|
|
47
|
-
`).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 o=s.map(m=>`${m.keywords.join(" ")} ${m.content}`),i=yt(this.memoryDir,`${t}_bm25_cache.json`),a=Fe(o,i),c=Ne(e,a),d=new Map(c.map(m=>[m.docIndex,m.score])),l=s.map((m,b)=>{let
|
|
47
|
+
`).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 o=s.map(m=>`${m.keywords.join(" ")} ${m.content}`),i=yt(this.memoryDir,`${t}_bm25_cache.json`),a=Fe(o,i),c=Ne(e,a),d=new Map(c.map(m=>[m.docIndex,m.score])),l=s.map((m,b)=>{let w=d.get(b)??0;return m.category==="secret"&&(w+=2),m.category==="commitment"&&(w+=1),{memory:m,score:w}}).filter(m=>m.score>0);if(l.length===0)return s.slice(-n);let g=l.sort((m,b)=>b.score-m.score).slice(0,n).map(m=>m.memory);if(g.length>0)try{this.recordAccess(t,g.map(m=>m.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(`
|
|
48
48
|
`)}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),s=new Set(t),o=!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(),o=!0}o&&Pn(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
49
49
|
`)+`
|
|
50
50
|
`)}getDueForReview(e,t=5){let n=this.getAll(e),s=Date.now();return n.filter(o=>o.category==="task-state"?!1:o.nextReview?new Date(o.nextReview).getTime()<=s:!0).sort((o,i)=>!o.nextReview&&i.nextReview?-1:o.nextReview&&!i.nextReview?1:o.nextReview&&i.nextReview?new Date(o.nextReview).getTime()-new Date(i.nextReview).getTime():(o.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 o=Math.round((Date.now()-new Date(s.createdAt).getTime())/864e5);n.push(`- [${s.category}] ${s.content} (${o}d old, accessed ${s.accessCount||0}x)`)}return n.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),n.join(`
|
|
@@ -132,24 +132,24 @@ Agent: ${t.slice(0,1e3)}`}],{model:yr,maxTokens:512})).content.trim().match(/\[[
|
|
|
132
132
|
`}return s}if(n==="user"&&t.message?.content){let s="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";s+=`${a}${Pe(i,800)}
|
|
133
133
|
`}return s}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
134
134
|
`:""}}var rs=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Xe;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;classifier;graphStore;handoverStore=new zt;activeSouls=new Map;taskOutputs=new Map;taskAborts=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 qe(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Jt(void 0,void 0,"unified"),this.memoryStore=new ze,this.patternStore=new Ze,this.rateLimiter=new Je,this.tokenTracker=new be,this.messageQueue=new Ye,Wn({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Gt({baseDir:L(process.cwd(),e.graph.baseDir),log:(...s)=>t("[graph]",...s)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new qt({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}setWorkflowAutoRunner(e){this.workflowAutoRunner=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 o=this.handoverStore.consumeSummary(t,n);if(!(!o&&s.summaryConsumedAt))return{fromAgent:s.fromAgent,summary:o||s.summary,at:s.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),s,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();n.includes(d)&&d.length>o&&(s=i,o=d.length)}return s}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[s,o]of this.agents)for(let i of o.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,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-B3EXXSEH.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let d=o.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,...d],source:{channel:s,chatId:o,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}}),this.sessions.setRotationMemo(e,s,o,c.memo,i),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,o]of this.agents)s!==e&&n.push({name:o.def.name,handle:this.getChannelHandle(s,t),role:o.def.systemPrompt?.split(`
|
|
135
|
-
`)[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,n,s){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,s)}catch(a){i={content:"",error:a?.message??String(a)}}if(e.intentRef)try{let a=i.error?/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Vt().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,s){let o=Ln().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(o){let y=await o;if(y.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${y.sessionId}`),{content:y.text,viaAttachedSession:y.sessionId};this.log(`[${e.agentId}] attached session did not take it (${y.reason}) \u2014 spawning`)}let i=this.agents.get(e.agentId);if(!i){if(this.meshFallback){let y=this.meshFallback.directory().find(h=>h.healthy&&h.skills.some(M=>M.id===e.agentId));if(y){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${y.peer}"`);try{let h=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(y.peer,e.message,e.agentId,{timeoutMs:h}),viaMesh:y.peer}}catch(h){return this.log(`[${e.agentId}] mesh fallback to "${y.peer}" failed: ${h?.message??h}`),{content:"",error:`mesh fallback failed: ${h?.message??h}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let a=e.context?.channel||"api",c=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(i.activeTasks>=i.def.maxConcurrent)if(a==="api"){let y=Date.now(),h=25*6e4,M=500;for(;i.activeTasks>=i.def.maxConcurrent;){if(Date.now()-y>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(h/6e4)}m`};await new Promise(
|
|
136
|
-
`).length}L`,Y=`[${e.agentId}] ${p}:${f} ${H} | session.messages=${h.length}`+(h.length>0?` first=${M.timestamp.slice(11,19)}(${M.role}:${(M.content||"").slice(0,40).replace(/\n/g," ")}) last=${
|
|
137
|
-
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${De.lookbackDays}d, turns=${y.turns.length}, scanned=${y.totalScanned}`)}}catch(y){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${y.message}`)}let as
|
|
135
|
+
`)[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,n,s){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,s)}catch(a){i={content:"",error:a?.message??String(a)}}if(e.intentRef)try{let a=i.error?/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Vt().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,s){let o=Ln().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(o){let y=await o;if(y.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${y.sessionId}`),{content:y.text,viaAttachedSession:y.sessionId};this.log(`[${e.agentId}] attached session did not take it (${y.reason}) \u2014 spawning`)}let i=this.agents.get(e.agentId);if(!i){if(this.meshFallback){let y=this.meshFallback.directory().find(h=>h.healthy&&h.skills.some(M=>M.id===e.agentId));if(y){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${y.peer}"`);try{let h=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(y.peer,e.message,e.agentId,{timeoutMs:h}),viaMesh:y.peer}}catch(h){return this.log(`[${e.agentId}] mesh fallback to "${y.peer}" failed: ${h?.message??h}`),{content:"",error:`mesh fallback failed: ${h?.message??h}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let a=e.context?.channel||"api",c=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(i.activeTasks>=i.def.maxConcurrent)if(a==="api"){let y=Date.now(),h=25*6e4,M=500;for(;i.activeTasks>=i.def.maxConcurrent;){if(Date.now()-y>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(h/6e4)}m`};await new Promise(N=>setTimeout(N,M))}}else{let y=i.def.queueMode||"collect",h=this.messageQueue.enqueue(e.agentId,a,c,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:a,chatId:c,originalContext:e.context});if(h==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(h){let M=this.messageQueue.pendingCount(e.agentId,a,c);return this.log(`[${e.agentId}] busy, message queued (mode: ${h}, pending: ${M})`),{content:"",error:`__queued__:${h}:${M}`}}}let d=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(y,h)=>{this.log(`[${e.agentId}] ${y} \u2014 queued, resumes in ~${Math.max(1,Math.round(h/1e3))}s`)}});if(!d.ok)return this.log(`[${e.agentId}] ${d.reason}`),{content:"",error:d.reason};i.activeTasks++,i.totalTasks++,i.lastActive=new Date;let u={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};i.runningTasks.push(u);let l=new AbortController;this.taskAborts.set(u.id,{agentId:e.agentId,channel:u.channel,chatId:typeof u.chatId=="string"?u.chatId:"",originalMessage:e.message||"",controller:l});let g={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(u.id,g);let m=y=>{if(y){g.buffer+=y,g.buffer.length>es&&(g.buffer=g.buffer.slice(g.buffer.length-es));for(let h of g.subscribers)try{h(y)}catch{}}},b=Le();e.taskId=b;let w=new Map,x;if(t){let y=no();x=h=>{let M=y(h);if(M&&m(M),ss(b,e.agentId,h),ns(w,h),s)try{s(h)}catch{}}}else x=y=>{if(ss(b,e.agentId,y),ns(w,y),s)try{s(y)}catch{}};this.messageQueue.markRunning(e.agentId,a,c),this.log(`[${e.agentId}] executing task (${i.activeTasks}/${i.def.maxConcurrent})`);let p=e.context?.channel||"api",f=e.context?.chatId||e.context?.group||e.context?.sender||"default",D=e.context?.sender||"User",C=i.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,p,f),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${p}:${f}`),ne().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"stale",at:new Date().toISOString()})),e.freshSession||await this.sessions.seedIfEmpty(e.agentId,p,f),this.sessions.addUserMessage(e.agentId,p,f,D,e.message);let T=Date.now();ne().emit("task:started",{agentId:e.agentId,channel:p,chatId:f,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(T).toISOString(),taskId:b});let $;if(this.classifier&&p!=="a2a"&&!C)try{$=await this.classifier.classify({text:e.message,channel:p,sender:e.context?.sender,agentId:e.agentId})||void 0}catch(y){this.log(`[classifier] classify failed for ${e.agentId}: ${y?.message||y}`)}let F=this.config.workflows?.matching,k;if(this.config.workflows?.enabled&&F?.enabled)try{let y=new nn({baseDir:L(process.cwd(),this.config.workflows.dir)}),h=sn({agentId:e.agentId,channel:p,message:e.message,intentPath:$?.path},y.list());h&&h.confidence>=F.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${h.workflow.id} confidence=${h.confidence.toFixed(2)} mode=${F.mode} reasons=${h.reasons.join(",")||"n/a"}`),F.mode==="auto"&&h.confidence>=F.autoRunThreshold&&(this.workflowAutoRunner?k={workflowId:h.workflow.id,confidence:h.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(y){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${y?.message||y}`)}let A=this.wikiHub.getAgentWiki(e.agentId),R=eo(A,e.agentId),S=this.memoryStore.findRelevant(e.message,e.agentId,C?3:8),I=this.memoryStore.buildContext(S),P=this.patternStore.findRelevant(e.message,e.agentId,5),E=this.patternStore.buildContext(P),W="";if(!C)try{let{loadLocalSkills:y,getAutoInjectSkills:h}=await import("./loader-5CA3O5GM.js"),M=await y(i.def.workspace);W=h(M,e.message)}catch{}let _=i.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,p,f):i.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,p,f):i.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,p,f):void 0;if(_&&this.sessions.isSessionStale(e.agentId,p,f)&&(this.log(`[${e.agentId}] session stale for ${p}:${f}, starting fresh`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,_,p,f,"stale"),this.sessions.clearClaudeSessionId(e.agentId,p,f),ne().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"stale",at:new Date().toISOString()}),_=void 0),_&&this.sessions.shouldRotateByTierTwo(e.agentId,p,f)){let y=this.sessions.getLastTurnContextTokens(e.agentId,p,f);this.log(`[${e.agentId}] tier-2 rotation for ${p}:${f} (last turn context: ${y} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,_,p,f,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,p,f),ne().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"tier-2",lastTurnInputTokens:y,at:new Date().toISOString()}),_=void 0}if(_&&this.sessions.shouldRotateByTurns(e.agentId,p,f)){let y=this.sessions.getTurnCount(e.agentId,p,f);this.log(`[${e.agentId}] max-turns rotation for ${p}:${f} (${y} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,_,p,f,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,p,f),ne().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"max-turns",at:new Date().toISOString()}),_=void 0}try{let y=await this.sessions.compactIfNeeded(e.agentId,p,f,this.memoryStore);if(y.compacted){let h=y.qualityScore??"?",M=y.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${p}:${f} (quality: ${h}%, ${M} entities lost)`),y.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${y.lostEntities.slice(0,5).join(", ")}`),y.drift){let N=y.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${N.overallScore} (lexicon=${N.lexiconDecay}, tools=${N.toolShift}, semantic=${N.semanticDrift})`),N.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${N.lostWords.slice(0,5).join(", ")}`)}}}catch(y){this.log(`[${e.agentId}] compaction failed (non-fatal): ${y.message}`)}let q=process.env.AGENTX_CONTEXT_SURGERY==="1",O=C?{maxMessages:8,maxChars:2400}:q&&Vn(p,i.def.tier)?{maxMessages:6,maxChars:1800}:void 0,J=_?void 0:this.sessions.buildHistoryContext(e.agentId,p,f,O),is=_?void 0:this.sessions.getRotationMemo(e.agentId,p,f)??void 0,Dt;if(this.config.procedures?.injection?.enabled&&!_&&!C)try{let y=new Me({baseDir:L(process.cwd(),this.config.procedures.dir)}),h=Mt(e.message,y.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(h.length>0){Dt=Rt(h);for(let M of h)this.log(`[${e.agentId}] procedure match ${M.procedure.meta.id} score=${M.score.toFixed(2)} (${M.reasons.join(",")})`)}}catch(y){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${y?.message||y}`)}if(ie&&ie.cat)try{let h=this.sessions.getSession(e.agentId,p,f).messages,M=h[0],N=h[h.length-1],H=J===void 0?`resume=${_?_.slice(0,8):"?"} (no rebuild)`:`fresh history=${J.length}c/${J.split(`
|
|
136
|
+
`).length}L`,Y=`[${e.agentId}] ${p}:${f} ${H} | session.messages=${h.length}`+(h.length>0?` first=${M.timestamp.slice(11,19)}(${M.role}:${(M.content||"").slice(0,40).replace(/\n/g," ")}) last=${N.timestamp.slice(11,19)}(${N.role}:${(N.content||"").slice(0,40).replace(/\n/g," ")})`:"");ie.cat("context",Y)}catch(y){ie.cat("context",`[${e.agentId}] context-diag error: ${y?.message??y}`)}let Ot;if(i.def.contextReferences&&!_)try{let y=i.def.workspace,h=this.referencesCache.get(y);if(!h){let[N,H]=await Promise.all([ct(i.def.workspace),dt(i.def.workspace)]);if(N.byId.size===0&&H.recipes.length===0){let[Y,v]=await Promise.all([ct(process.cwd()),dt(process.cwd())]);h={refs:Y,recipes:v}}else h={refs:N,recipes:H};this.referencesCache.set(y,h)}let M=en({agentId:e.agentId,intentTags:$?.path,message:e.message},h.recipes,h.refs);M.cards.length>0&&(Ot=Zt(M.cards,500*4)),M.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${M.unresolvedIds.join(", ")}`)}catch(y){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${y?.message||y}`)}let _t=this.sessions.getCrossSessionSummary(e.agentId,p,f,e.message),Et,De=In(e.message);if(De)try{let y=this.sessions.recallTurns({agentId:e.agentId,channel:p,chatId:f,lookbackDays:De.lookbackDays,limit:12});if(y.turns.length>0){let h=[`[Long-memory recall \u2014 last ${De.lookbackDays}d on this chat (cue-triggered)]`],M=[...y.turns].sort((N,H)=>N.ts.localeCompare(H.ts));for(let N of M){let H=N.ts.slice(11,16)+" "+N.day,Y=N.role==="user"?N.senderName||"User":N.senderName||"Agent";h.push(`${H} ${Y}: ${N.content}`)}y.hasMore&&h.push(`[\u2026${y.totalScanned-y.turns.length}+ older turns available \u2014 call /recall with before=${y.oldestTs} to walk further back]`),h.push("[End of long-memory recall \u2014 respond to the latest message above]"),Et=h.join(`
|
|
137
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${De.lookbackDays}d, turns=${y.turns.length}, scanned=${y.totalScanned}`)}}catch(y){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${y.message}`)}let as=C?"layered":e.contextStrategy??i.def.contextStrategy??this.config.session.contextStrategy??"layered",Nt,Ft,jt=!1;if(as==="planner"){try{let{planContext:y}=await import("./context-planner-45GEWKGL.js"),h=await y({agentId:e.agentId,channel:p,chatId:f,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore});h?(jt=!0,Nt=h.sessionHistory,I=h.memoryContext,_t=h.crossChatContext,Ft=h.debug,this.log(`[${e.agentId}] planner: turns=${h.debug.recentTurns}, mem=${h.debug.memoryIncluded?"yes":"no"}, xchat=${h.debug.crossChatIncluded?"yes":"no"} (${h.debug.planLatencyMs}ms) \u2014 ${h.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(y){this.log(`[${e.agentId}] planner failed (non-fatal): ${y.message} \u2014 falling back to layered (keeping --resume for continuity)`)}jt&&_&&(this.sessions.clearClaudeSessionId(e.agentId,p,f),_=void 0)}let nt=`${e.agentId}:${p}:${f}`,Oe=Yt(e.message);Oe&&(Oe==="default"?(this.activeSouls.delete(nt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(nt,Oe),this.log(`[${e.agentId}] Soul switched to: ${Oe}`)));let cs=this.activeSouls.get(nt),ds=Qt(i.def.workspace,cs),us=Xt(ds),ls=this.agentMemory.indexMarkdown(e.agentId),gs=i.def.tier==="claude-code"||i.def.tier==="codex-cli"?`[Operating principle]
|
|
138
138
|
Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`:"",ps=i.def.richMessages!==!1&&(p==="telegram"||p==="whatsapp")?["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text."].join(`
|
|
139
139
|
`):"",Lt="";if(i.def.workspace){let y=L(i.def.workspace,"CLAUDE.md");if(Q(y))try{let h=Re(y,"utf-8");Lt=`[Project CLAUDE.md]
|
|
140
140
|
${h.length>4e3?h.slice(0,4e3)+`
|
|
141
141
|
|
|
142
|
-
[CLAUDE.md truncated to 4KB]`:h}`}catch{}}let _e=e.context?.runbookPath,st=[];if(_e&&Q(_e)){let y=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],h=0,M=4e3,
|
|
142
|
+
[CLAUDE.md truncated to 4KB]`:h}`}catch{}}let _e=e.context?.runbookPath,st=[];if(_e&&Q(_e)){let y=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],h=0,M=4e3,N=16e3;for(let H of y){if(h>=N)break;let Y=L(_e,H);if(Q(Y))try{let v=Re(Y,"utf-8"),X=v.length>M?v.slice(0,M)+`
|
|
143
143
|
|
|
144
144
|
[${H} truncated to ${M} bytes]`:v;st.push(`[Project Runbook \u2014 ${H} from ${_e}]
|
|
145
145
|
${X}`),h+=X.length}catch{}}}let fs=st.length>0?st.join(`
|
|
146
146
|
|
|
147
147
|
`):"",rt=[i.def.systemPrompt||"",gs,ps,Lt,fs,us||"",ls||""].filter(y=>y.trim().length>0).join(`
|
|
148
148
|
|
|
149
|
-
`)||void 0,hs={channel:p,chatId:f,channelScope:e.context?.group?"group":p==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:i.def.name,agentHandle:this.getChannelHandle(e.agentId,p),systemPrompt:i.def.systemPrompt,sender:
|
|
150
|
-
`),M=!1)},Y=y?h:h?(j,G)=>{H(),h(j,G)}:void 0,v=await wn(i.def,ms,this.providers,Y,ot,
|
|
149
|
+
`)||void 0,hs={channel:p,chatId:f,channelScope:e.context?.group?"group":p==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:i.def.name,agentHandle:this.getChannelHandle(e.agentId,p),systemPrompt:i.def.systemPrompt,sender:D,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:C||Vn(p,i.def.tier)?void 0: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:E||void 0,procedureContext:Dt,references:Ot,skillInjection:W||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Nt??J,memoryContext:I||void 0,crossChatContext:_t||void 0,longMemoryRecall:Et||void 0,wikiContext:C?void 0:R,handoverNote:this.buildHandoverNote(e.agentId,p,f),rotationMemo:is,intent:$?{path:$.path,pathLabel:$.pathLabel,pathId:$.pathId,axes:$.axes,leaf:$.leaf,status:$.status}:void 0,message:e.message},ot=Rn(hs,C?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),it=(ot?.length??0)+(rt?.length??0)+(e.message?.length??0),Ee={history:ot?.length??0,sysPrompt:rt?.length??0,message:e.message?.length??0},Ht=zn(e.agentId,p,f);Qn(Ht,it,Ee);let Ut=Xn(Ht);Ut&&this.log(`[${e.agentId}] ${Ut}`),it>16e3&&this.log(`[${e.agentId}] large context for ${p}:${f}: ${it} bytes (history=${Ee.history}, sysPrompt=${Ee.sysPrompt}, message=${Ee.message})`);let ms={...e,systemPromptAppend:rt},Z;try{if(k&&this.workflowAutoRunner)try{let j=await this.workflowAutoRunner({workflowId:k.workflowId,agentId:e.agentId,channel:p,chatId:f,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:p,chatId:f,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:$?.path,matchedWorkflowId:k.workflowId,matchConfidence:k.confidence}});return this.log(`[${e.agentId}] workflow auto-run started ${k.workflowId} run=${j.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),Z={content:"",duration:0,metadata:{handledByWorkflow:k.workflowId,workflowRunId:j.runId,workflowMatchConfidence:k.confidence}},Z}catch(j){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${j?.message||j}`)}if(i.def.tier==="claude-code"){let j=i.def.persistentProcess?We():null,G=j!=null&&j.hasLive({agentId:e.agentId,channel:p,chatId:f}),ge=!!_||G,oe=[Hn(ge),qn(ge)].find(we=>we&&we.abort);if(oe){i.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${oe.reason}`);let we={content:"",error:oe.message,duration:0};if(!t){g.buffer=`[error] ${oe.message}`;for(let ys of g.subscribers)try{ys(g.buffer)}catch{}}return Z=we,we}Bn();let Wt=Jn();Wt&&this.log(`[${e.agentId}] ${Wt}`)}let y=i.def.tier==="claude-code",h=y?t:(j,G)=>{j&&m(j),t&&t(j,G)},M=!1,N=y?n:j=>{j&&(M?m(j):(m(`\u{1F4AD} ${j}`),M=!0)),n&&n(j)},H=()=>{M&&(m(`
|
|
150
|
+
`),M=!1)},Y=y?h:h?(j,G)=>{H(),h(j,G)}:void 0,v=await wn(i.def,ms,this.providers,Y,ot,_,x,l.signal,N);if(!v.error){let j=to(i.def.toolUseRequired,w);if(j){let G=Array.from(w.entries()).map(([ge,re])=>`${ge}=${re}`).join(", ")||"none";v.error=`tool_required_not_called: ${j} (invoked: ${G})`,v.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${j}, observed ${G}`)}}Z=v;let X=v.usage?An(v.usage):void 0;if(ne().emit("task:completed",{taskId:b,agentId:e.agentId,channel:p,chatId:f,durationMs:Date.now()-T,error:v.error||void 0,inputTokens:X?.inputTokens,outputTokens:X?.outputTokens,cacheReadTokens:X?.cacheReadTokens,cacheCreateTokens:X?.cacheCreateTokens,tier2InputTokens:X?.tier2InputTokens,tier2OutputTokens:X?.tier2OutputTokens,tier2CacheReadTokens:X?.tier2CacheReadTokens,tier2CacheCreateTokens:X?.tier2CacheCreateTokens,finalResponse:v.content||void 0,billedModel:v.billedModel||i.def.model||void 0,at:new Date().toISOString()}),!t&&(v.content||v.error)){let j=v.error?`[error] ${v.error}`:v.content;g.buffer=j;for(let G of g.subscribers)try{G(j)}catch{}}if(v.error)i.errors++,this.log(`[${e.agentId}] error: ${v.error}`);else{if(this.sessions.addAgentMessage(e.agentId,p,f,v.content),v.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,p,f,v.claudeSessionId),v.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,p,f,v.codexSessionId),v.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,p,f,v.opencodeSessionId),(v.claudeSessionId||v.codexSessionId||v.opencodeSessionId)&&v.usage&&this.sessions.recordTurnUsage(e.agentId,p,f,v.usage,v.contextTokens),v.usage){let re=v.contextTokens,oe=(v.usage.inputTokens||0)+(v.usage.cacheReadTokens||0)+(v.usage.cacheCreateTokens||0);(re??oe)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${p}:${f}: context=${re??"n/a"} tokens (cumulative turn total=${oe}) \u2014 next turn will rotate`)}if(v.content.length>50){try{let re=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:re,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:p,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
151
151
|
|
|
152
|
-
Agent: ${v.content}`,meta
|
|
152
|
+
Agent: ${v.content}`,meta:$?.path?.length?{intentPath:$.path,intentPathLabel:$.pathLabel}:void 0})}catch{}Bt(e.agentId,e.message,v.content,{channel:p,chatId:f,sender:D},this.memoryStore).catch(()=>{}),Fn(e.agentId,e.message,v.content,{channel:p,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let j=v.billedModel||e.model||i.def.model,G=e.context?.channel,ge=G&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${G}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,v.duration||0,v.usage,e.message.length,v.content.length,!1,j,G,ge),this.log(`[${e.agentId}] completed in ${v.duration}ms`+(v.tokensUsed?` (${v.tokensUsed} tokens)`:""))}return v}catch(y){i.errors++,this.log(`[${e.agentId}] unexpected error: ${y.message}`);let h=He(y.message);return Z={content:"",error:Ue(h),errorKind:h.kind},Z}finally{i.activeTasks--;let y=i.runningTasks.findIndex(h=>h.id===u.id);y!==-1&&i.runningTasks.splice(y,1),this.taskAborts.delete(u.id),g.done=!0,g.endedAt=new Date;for(let h of g.subscribers)try{h(`
|
|
153
153
|
[task finished]
|
|
154
|
-
`)}catch{}g.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(u.id),Zr).unref?.();try{let h=g.endedAt,M={id:u.id,agentId:e.agentId,channel:u.channel,chatId:u.chatId,sender:u.sender,message:e.message||"",startedAt:u.startedAt.toISOString(),endedAt:h.toISOString(),durationMs:h.getTime()-u.startedAt.getTime(),ok:!Z?.error,error:Z?.error,responseText:Z?.content||"",transcript:g.buffer};this.persistTaskRecord(M);let
|
|
155
|
-
//# sourceMappingURL=chunk-
|
|
154
|
+
`)}catch{}g.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(u.id),Zr).unref?.();try{let h=g.endedAt,M={id:u.id,agentId:e.agentId,channel:u.channel,chatId:u.chatId,sender:u.sender,message:e.message||"",startedAt:u.startedAt.toISOString(),endedAt:h.toISOString(),durationMs:h.getTime()-u.startedAt.getTime(),ok:!Z?.error,error:Z?.error,responseText:Z?.content||"",transcript:g.buffer};this.persistTaskRecord(M);let N=(M.responseText||M.error||"").trim();if(N){let H=N.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:H,at:h,ok:M.ok})}}catch(h){this.log(`[${e.agentId}] task history persist failed: ${h?.message}`)}this.messageQueue.markDone(e.agentId,a,c).then(h=>{if(h.length!==0){this.log(`[${e.agentId}] flushing ${h.length} queued message(s)`);for(let M of h){let N=M.originalContext||{channel:M.channel,sender:M.sender,chatId:M.chatId};this.execute({message:M.text,agentId:e.agentId,context:N}).then(H=>this.postQueuedResponseToChannel(e.agentId,N,H)).catch(H=>{this.log(`[${e.agentId}] queued message failed: ${H.message}`)})}}}).catch(h=>{this.log(`[${e.agentId}] queue flush failed: ${h.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=L(process.cwd(),xe,this.safe(e.agentId),t);Q(n)||Qr(n,{recursive:!0});let s=L(n,`${this.safe(e.id)}.json`);Yr(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 o=new Array(t).fill(0),i=n-t*36e5,a=L(process.cwd(),xe,this.safe(e));if(!Q(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),d=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let l of[d,c]){let g=L(a,l);if(Q(g))try{for(let m of V(g)){if(!m.endsWith(".json"))continue;let b=m.split("-")[0],w=parseInt(b,10);if(!Number.isFinite(w)||w<i||w>n)continue;let x=Math.floor((n-w)/36e5),p=t-1-x;p>=0&&p<t&&o[p]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=L(process.cwd(),xe);if(!Q(e))return 0;let t=0;for(let n of V(e)){let s=L(e,n),o;try{o=V(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=L(s,i),c;try{c=V(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(Re(L(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let g=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:g,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Vr){let t=L(process.cwd(),xe);if(!Q(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=0;for(let o of V(t)){let i=L(t,o),a;try{a=V(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{Xr(L(i,c),{recursive:!0,force:!0}),s++}catch{}}}return s}listTaskHistory(e,t=50){let n=L(process.cwd(),xe,this.safe(e));if(!Q(n))return[];let s=V(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of s){if(o.length>=t)break;let a=L(n,i),c;try{c=V(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(Re(L(a,d),"utf-8")),{transcript:l,responseText:g,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let n=L(process.cwd(),xe,this.safe(e));if(!Q(n))return null;let s=this.safe(t),o=V(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=L(n,i,`${s}.json`);if(Q(a))try{return JSON.parse(Re(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let s=tn();if(!s)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.error?.startsWith("__queued__"))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&s.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}queueFollowUp(e,t,n,s={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let g=this.messageQueue.pendingCount(i,a,c),m=!1;if(s.replace){let b=s.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),m=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${g}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:m,edited:l,pending: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{ro as a,on as b,Cs as c,As as d,Ds as e,Os as f,_s as g,wn as h,qe as i,Je as j,Xe as k,ne as l,jn as m,wr as n,Ln as o,Me as p,Br as q,Gr as r,qr as s,Jr as t,zr as u,Mt as v,Vi as w,ea as x,Pt as y,ts as z,ns as A,to as B,ss as C,rs as D};
|
|
155
|
+
//# sourceMappingURL=chunk-E5CXCI33.js.map
|