agentix-cli 0.27.0 → 0.28.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 +67 -118
- package/apps/mac-helper/Sources/AgentXHelper/AXTree.swift +159 -0
- package/apps/mac-helper/Sources/AgentXHelper/Brand.swift +63 -0
- package/apps/mac-helper/Sources/AgentXHelper/Focus.swift +97 -0
- package/apps/mac-helper/Sources/AgentXHelper/HUD.swift +179 -0
- package/apps/mac-helper/Sources/AgentXHelper/OCR.swift +117 -0
- package/apps/mac-helper/Sources/AgentXHelper/Pointer.swift +309 -0
- package/apps/mac-helper/Sources/AgentXHelper/Screens.swift +67 -0
- package/apps/mac-helper/Sources/AgentXHelper/Typer.swift +185 -0
- package/apps/mac-helper/Sources/AgentXHelper/Vision.swift +201 -0
- package/apps/mac-helper/Sources/AgentXHelper/main.swift +265 -0
- package/apps/mac-helper/build.sh +39 -0
- package/apps/mac-voice/Resources/Info.plist +18 -0
- package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +108 -0
- package/apps/mac-voice/Sources/AgentXVoice/Brand.swift +123 -0
- package/apps/mac-voice/Sources/AgentXVoice/Config.swift +68 -0
- package/apps/mac-voice/Sources/AgentXVoice/Hold.swift +74 -0
- package/apps/mac-voice/Sources/AgentXVoice/Hotkey.swift +76 -0
- package/apps/mac-voice/Sources/AgentXVoice/Markdown.swift +140 -0
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +275 -0
- package/apps/mac-voice/Sources/AgentXVoice/Progress.swift +147 -0
- package/apps/mac-voice/Sources/AgentXVoice/Recorder.swift +139 -0
- package/apps/mac-voice/Sources/AgentXVoice/ResultCard.swift +162 -0
- package/apps/mac-voice/Sources/AgentXVoice/SmartPaste.swift +72 -0
- package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +192 -0
- package/apps/mac-voice/Sources/AgentXVoice/StepLabel.swift +159 -0
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +380 -0
- package/apps/mac-voice/build.sh +32 -0
- package/dist/{App-U52IPUK2.js → App-CKPH3HHF.js} +2 -2
- package/dist/{ChatApp-XP4OMHPL.js → ChatApp-MX7IG4K2.js} +2 -2
- package/dist/{agent-V2CA4TXD.js → agent-2U574KBZ.js} +2 -2
- package/dist/{board-dashboard-TTMAYRLG.js → board-dashboard-QR7CVTKA.js} +8 -10
- package/dist/board-dashboard-QR7CVTKA.js.map +1 -0
- package/dist/{chunk-UFAGYX73.js → chunk-3LYM22IV.js} +8 -8
- package/dist/chunk-3LYM22IV.js.map +1 -0
- package/dist/{chunk-VTE7L6LO.js → chunk-5IA2CYHN.js} +2 -2
- package/dist/{chunk-GDWJUGB5.js → chunk-64CAIB3C.js} +2 -2
- package/dist/{chunk-WZ72HX5C.js → chunk-E3UJHQGN.js} +145 -138
- package/dist/chunk-E3UJHQGN.js.map +1 -0
- package/dist/{chunk-IB3F7VBE.js → chunk-G2HMRDUQ.js} +3 -3
- package/dist/chunk-G2HMRDUQ.js.map +1 -0
- package/dist/{chunk-IBUSGCLQ.js → chunk-H2QQU2XV.js} +2 -2
- package/dist/{chunk-BPIRO4YD.js → chunk-MHIMGM4G.js} +2 -2
- package/dist/{chunk-CJQQIRPD.js → chunk-P5ZBBEPL.js} +7 -7
- package/dist/{chunk-CJQQIRPD.js.map → chunk-P5ZBBEPL.js.map} +1 -1
- package/dist/{chunk-L2IZPR6P.js → chunk-QHTQPBHU.js} +2 -2
- package/dist/chunk-S2MNL5V6.js +2 -0
- package/dist/chunk-S2MNL5V6.js.map +1 -0
- package/dist/{chunk-2T5W3ETS.js → chunk-SCTIUFL4.js} +2 -2
- package/dist/{chunk-OPHIXXGI.js → chunk-ULLAE6LE.js} +52 -52
- package/dist/chunk-ULLAE6LE.js.map +1 -0
- package/dist/{chunk-LNRB5MCU.js → chunk-VIH7ARPF.js} +151 -134
- package/dist/chunk-VIH7ARPF.js.map +1 -0
- package/dist/{chunk-DCDQZR7I.js → chunk-YLBERT7N.js} +6 -6
- package/dist/chunk-YLBERT7N.js.map +1 -0
- package/dist/{chunk-AX2PWSRT.js → chunk-YLGIZRHV.js} +2 -2
- package/dist/{chunk-FIEJDZVC.js → chunk-ZMYGXHPT.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-ZLSXGPTV.js +2 -0
- package/dist/config-HMW3EBZL.js +2 -0
- package/dist/config-mutator-4SZ5YEVD.js +2 -0
- package/dist/doctor-LRYV3QLK.js +2 -0
- package/dist/index.d.ts +37 -12
- package/dist/index.js +12 -19
- package/dist/index.js.map +1 -1
- package/dist/program-GSZ5AYAM.js +2 -0
- package/dist/query-SQDHE4HV.js +2 -0
- package/dist/registry-LE6FWYZC.js +2 -0
- package/dist/{review-candidates-AEUXRQQC.js → review-candidates-RQU5KNZM.js} +2 -2
- package/dist/routing-ILERJXB6.js +2 -0
- package/dist/scheduler-BFM3EINS.js +2 -0
- package/dist/{seat-VZ7AVO27.js → seat-7WM7II2B.js} +2 -2
- package/dist/{select-F5I5PO2O.js → select-X4KVMOP5.js} +2 -2
- package/dist/wiki-2AUFSIKO.js +2 -0
- package/dist/wiki-2AUFSIKO.js.map +1 -0
- package/package.json +14 -3
- package/scripts/postinstall.mjs +80 -0
- package/dist/board-dashboard-TTMAYRLG.js.map +0 -1
- package/dist/chunk-DCDQZR7I.js.map +0 -1
- package/dist/chunk-IB3F7VBE.js.map +0 -1
- package/dist/chunk-LNRB5MCU.js.map +0 -1
- package/dist/chunk-OPHIXXGI.js.map +0 -1
- package/dist/chunk-UFAGYX73.js.map +0 -1
- package/dist/chunk-WZ72HX5C.js.map +0 -1
- package/dist/client-PX25MD47.js +0 -2
- package/dist/config-HL5F36V4.js +0 -2
- package/dist/config-mutator-HBX53OMJ.js +0 -2
- package/dist/doctor-PBAH6XL3.js +0 -2
- package/dist/program-YGXVCV2Y.js +0 -2
- package/dist/query-ZKTFJMNE.js +0 -2
- package/dist/registry-PSZDPFZK.js +0 -2
- package/dist/routing-4PV66BK6.js +0 -2
- package/dist/routing-4PV66BK6.js.map +0 -1
- package/dist/scheduler-GZZAN6ZG.js +0 -2
- package/dist/wiki-N5SMP3DT.js +0 -2
- /package/dist/{App-U52IPUK2.js.map → App-CKPH3HHF.js.map} +0 -0
- /package/dist/{ChatApp-XP4OMHPL.js.map → ChatApp-MX7IG4K2.js.map} +0 -0
- /package/dist/{agent-V2CA4TXD.js.map → agent-2U574KBZ.js.map} +0 -0
- /package/dist/{chunk-VTE7L6LO.js.map → chunk-5IA2CYHN.js.map} +0 -0
- /package/dist/{chunk-GDWJUGB5.js.map → chunk-64CAIB3C.js.map} +0 -0
- /package/dist/{chunk-IBUSGCLQ.js.map → chunk-H2QQU2XV.js.map} +0 -0
- /package/dist/{chunk-BPIRO4YD.js.map → chunk-MHIMGM4G.js.map} +0 -0
- /package/dist/{chunk-L2IZPR6P.js.map → chunk-QHTQPBHU.js.map} +0 -0
- /package/dist/{chunk-2T5W3ETS.js.map → chunk-SCTIUFL4.js.map} +0 -0
- /package/dist/{chunk-AX2PWSRT.js.map → chunk-YLGIZRHV.js.map} +0 -0
- /package/dist/{chunk-FIEJDZVC.js.map → chunk-ZMYGXHPT.js.map} +0 -0
- /package/dist/{client-PX25MD47.js.map → client-ZLSXGPTV.js.map} +0 -0
- /package/dist/{config-HL5F36V4.js.map → config-HMW3EBZL.js.map} +0 -0
- /package/dist/{config-mutator-HBX53OMJ.js.map → config-mutator-4SZ5YEVD.js.map} +0 -0
- /package/dist/{doctor-PBAH6XL3.js.map → doctor-LRYV3QLK.js.map} +0 -0
- /package/dist/{program-YGXVCV2Y.js.map → program-GSZ5AYAM.js.map} +0 -0
- /package/dist/{query-ZKTFJMNE.js.map → query-SQDHE4HV.js.map} +0 -0
- /package/dist/{registry-PSZDPFZK.js.map → registry-LE6FWYZC.js.map} +0 -0
- /package/dist/{review-candidates-AEUXRQQC.js.map → review-candidates-RQU5KNZM.js.map} +0 -0
- /package/dist/{scheduler-GZZAN6ZG.js.map → routing-ILERJXB6.js.map} +0 -0
- /package/dist/{seat-VZ7AVO27.js.map → scheduler-BFM3EINS.js.map} +0 -0
- /package/dist/{wiki-N5SMP3DT.js.map → seat-7WM7II2B.js.map} +0 -0
- /package/dist/{select-F5I5PO2O.js.map → select-X4KVMOP5.js.map} +0 -0
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
import{a as Vt,g as cn,m as dn}from"./chunk-GDWJUGB5.js";import{c as zt,e as en,f as tn,h as nn}from"./chunk-67Q4DCPS.js";import{a as an}from"./chunk-W4YR2RO2.js";import{b as rn}from"./chunk-FIEJDZVC.js";import{a as Qt}from"./chunk-77OV7346.js";import{b as Yt,c as Xt,f as Zt}from"./chunk-IBUSGCLQ.js";import{a as He,b as ut}from"./chunk-EVWEG3VD.js";import{v as Jt,w as Ps}from"./chunk-AX2PWSRT.js";import{a as dt,f as Rs}from"./chunk-F4HZTZHW.js";import{a as je,b as Gt}from"./chunk-ZTEU5JVQ.js";import{c as Fe,d as Le}from"./chunk-QOYAX2FT.js";import{a as lt,b as sn}from"./chunk-WPMX3VGI.js";import{a as gt,b as on}from"./chunk-K33GIBSE.js";import{e as ie}from"./chunk-DSYKYZMT.js";Ps();Rs();var un="session-continuity",ln={continues:dt("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:dt("Does the new request refer to something stated earlier in the conversation?")};function gn(r){let e=(r.recentRequests??[]).filter(Boolean);return{newRequest:pt(r.message,1200),previousRequest:r.previousMessage?pt(r.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>pt(t,400))}:{},minutesSinceLastTurn:r.minutesSinceLastTurn,turnsSoFar:r.turnCount,currentContextTokens:r.lastTurnContextTokens,agent:r.agentId,channel:r.channel}}function pn(r,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=r.continues.noul,s=r.needsHistory.noul;return n<=t&&s<=t}function pt(r,e){let t=String(r??"");return t.length>e?t.slice(0,e):t}import{execa as Ge}from"execa";import{execFile as Ds}from"child_process";import{StringDecoder as ke}from"string_decoder";import{mkdtempSync as xn,readFileSync as wn,rmSync as Tn}from"fs";import{join as Be}from"path";import{tmpdir as kn}from"os";function Ue(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 We(r){return r.fix?`${r.message} \u2014 ${r.fix}`:r.message}var fn=null;function Ke(){return fn}function So(r){fn=r}function Te(r){return`${r.agentId}:${r.channel}:${r.chatId}`}var ge=class extends Error{constructor(t,n,s){super(t);this.scope=n;this.cap=s;this.name="RegistryCapExceeded"}},mn=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 ge(`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 ge(`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=Ue(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
|
-
`)}return{error:We(e),errorKind:e.kind}}function
|
|
1
|
+
import{a as tn,g as un,m as ln}from"./chunk-64CAIB3C.js";import{c as Yt,e as nn,f as sn,h as rn}from"./chunk-67Q4DCPS.js";import{a as gt,b as cn}from"./chunk-K33GIBSE.js";import{a as dn}from"./chunk-W4YR2RO2.js";import{b as an}from"./chunk-ZMYGXHPT.js";import{a as Qt}from"./chunk-S2MNL5V6.js";import{a as Xt}from"./chunk-77OV7346.js";import{b as Zt,c as Vt,f as en}from"./chunk-H2QQU2XV.js";import{a as He,b as ut}from"./chunk-EVWEG3VD.js";import{v as zt,w as _s}from"./chunk-YLGIZRHV.js";import{a as dt,f as Ds}from"./chunk-F4HZTZHW.js";import{a as je,b as Jt}from"./chunk-ZTEU5JVQ.js";import{c as Fe,d as Le}from"./chunk-QOYAX2FT.js";import{a as lt,b as on}from"./chunk-WPMX3VGI.js";import{e as ie}from"./chunk-DSYKYZMT.js";_s();Ds();var gn="session-continuity",pn={continues:dt("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:dt("Does the new request refer to something stated earlier in the conversation?")};function fn(r){let e=(r.recentRequests??[]).filter(Boolean);return{newRequest:pt(r.message,1200),previousRequest:r.previousMessage?pt(r.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>pt(t,400))}:{},minutesSinceLastTurn:r.minutesSinceLastTurn,turnsSoFar:r.turnCount,currentContextTokens:r.lastTurnContextTokens,agent:r.agentId,channel:r.channel}}function mn(r,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=r.continues.noul,s=r.needsHistory.noul;return n<=t&&s<=t}function pt(r,e){let t=String(r??"");return t.length>e?t.slice(0,e):t}import{execa as Ge}from"execa";import{execFile as Os}from"child_process";import{StringDecoder as ke}from"string_decoder";import{mkdtempSync as Tn,readFileSync as kn,rmSync as In}from"fs";import{join as Be}from"path";import{tmpdir as Sn}from"os";function Ue(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 We(r){return r.fix?`${r.message} \u2014 ${r.fix}`:r.message}var hn=null;function Ke(){return hn}function vo(r){hn=r}function Te(r){return`${r.agentId}:${r.channel}:${r.chatId}`}var ge=class extends Error{constructor(t,n,s){super(t);this.scope=n;this.cap=s;this.name="RegistryCapExceeded"}},yn=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 ge(`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 ge(`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=Ue(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
|
+
`)}return{error:We(e),errorKind:e.kind}}function Cn(){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 qe(){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 bn(){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
|
-
`)}function
|
|
4
|
+
`)}function vn(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 $n(r,e){return!e||e.trim().length===0?r:`[System]
|
|
5
5
|
${e.trim()}
|
|
6
6
|
|
|
7
7
|
[User]
|
|
8
|
-
${r}`}function
|
|
9
|
-
`))if(i.trim())try{let a=JSON.parse(i);t=mt(a)||t,n
|
|
10
|
-
`)}function
|
|
8
|
+
${r}`}function Es(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($n(e,n)),o}function Ns(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 xn(r){return JSON.stringify(r)}function Fs(){let r=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${xn(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[r,"serve","--stdio","--cwd",process.cwd()].map(xn).join(",")}]`]}function An(r,e,t,n,s,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...Fs()),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($n(e,s)),a}function ft(r,e){let t=He(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 Ls(r,e){let t=ft(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 js(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 se(...r){for(let e of r)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function mt(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:se(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:se(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:se(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:se(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[r.msg,r.message,r.response,r.result,r.item]){let s=mt(n,e+1);if(s)return s}}function Mn(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 ht(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=ht(t,e+1);if(n)return n}}}function Hs(r){let e=typeof r=="string"?r:r?.toString("utf8")||"",t,n,s,o;for(let i of e.split(`
|
|
9
|
+
`))if(i.trim())try{let a=JSON.parse(i);t=mt(a)||t,n=Mn(a)||n,s=ht(a)||s,o=Rn(a)||o}catch{}return{usage:t,billedModel:n,sessionId:s,apiError:o}}function Rn(r){if(!(!r||typeof r!="object")){if(r.type==="error"&&typeof r.message=="string")return wn(r.message);if(r.type==="turn.failed"){let e=r.error?.message??r.error;if(typeof e=="string")return wn(e)}}}function wn(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 Us(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 yt(r,e,t,n,s){let o=Us(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 Ws(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 Ks(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,numTurns:typeof e.num_turns=="number"?e.num_turns:void 0}}catch{return{text:r}}}async function Bs(r,e,t,n,s){let o=Date.now(),i=ae(r,e,t),a=vn(r,i,!1,n,e.model,e.systemPromptAppend);if(yt(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:y}=await new Promise(w=>{let p=ut(He(r.workspace)),m=!1,P=Os("claude",a,{cwd:r.workspace,timeout:d,maxBuffer:10*1024*1024,env:{...p,HOME:p.HOME||"/home/"+(p.USER||"user")}},(I,S,$)=>{w({stdout:S||"",stderr:$||"",exitCode:I?I.code??1:0,killed:m})});if(P.stdin?.end(),s){let I=()=>{m=!0,c=s.reason?.message||(typeof s.reason=="string"?s.reason:"task cancelled by operator");try{P.kill("SIGTERM")}catch{}setTimeout(()=>{try{P.killed||P.kill("SIGKILL")}catch{}},3e3).unref?.()};s.aborted?I():s.addEventListener("abort",I,{once:!0})}});if(y)return{content:"",error:c||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!u&&g!==0){let w;return g===143?w=`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||"")?w=Cn():w=l?.trim()||`Claude Code exited with code ${g}`,{content:"",...K(w),duration:Date.now()-o}}let b=Ws(u);if(b)return{content:"",...K(b),duration:Date.now()-o};let x=Ks(u);return{content:x.text,duration:Date.now()-o,claudeSessionId:x.sessionId,usage:x.usage,numTurns:x.numTurns,billedModel:x.billedModel}}catch(d){return console.error(`[runtime] execFile threw: ${d.message}`),{content:"",error:d.message||"Claude Code failed",duration:Date.now()-o}}}async function qs(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=vn(r,c,!0,s,e.model,e.systemPromptAppend);yt(e.agentId,r,e.model,s,"stream");let u="",l,g,y,b,x,w;try{let p=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),m=ut(He(r.workspace)),P=Ge("claude",d,{cwd:r.workspace,timeout:p,reject:!1,env:m,extendEnv:!1,buffer:!1,stdin:"ignore"}),I=!1,S;if(i){let k=()=>{I=!0,S=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{P.kill("SIGTERM")}catch{}setTimeout(()=>{try{P.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?k():i.addEventListener("abort",k,{once:!0})}let $="",L=new ke("utf8");P.stdout&&P.stdout.on("data",k=>{$+=L.write(k);let C=$.split(`
|
|
11
11
|
`);$=C.pop()||"";for(let _ of C)if(_.trim())try{let T=JSON.parse(_);if(o)try{o(T)}catch{}if(T.type==="assistant"&&T.message?.usage){let D=T.message.usage,A=(D.input_tokens||0)+(D.cache_read_input_tokens||0)+(D.cache_creation_input_tokens||0);A>0&&(b=A)}if(T.type==="assistant"&&T.message?.content){for(let D of T.message.content)if(D.type==="text"&&D.text){let A=D.text.slice(u.length);A&&(u=D.text,t(A,u))}}if(T.type==="content_block_delta"&&T.delta?.text&&(u+=T.delta.text,t(T.delta.text,u)),T.type==="result"&&T.result){if(T.is_error&&typeof T.result=="string")w=T.result;else{let D=(typeof T.result=="string",T.result);if(typeof D=="string"&&D.length>u.length){let A=D.slice(u.length);u=D,A&&t(A,u)}}T.usage&&(g={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.model=="string"&&(l=T.model),typeof T.session_id=="string"&&(y=T.session_id),typeof T.num_turns=="number"&&(x=T.num_turns)}T.type==="system"&&T.subtype==="init"&&(typeof T.model=="string"&&(l=T.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${T.apiKeySource} version=${T.claude_code_version} model=${T.model} permMode=${T.permissionMode}
|
|
12
12
|
`))}catch{_.trim()&&!_.startsWith("{")&&(u+=_+`
|
|
13
13
|
`,t(_+`
|
|
14
|
-
`,u))}});let R=await P,E=L.end();if(E&&($+=E),I)return{content:"",error:S||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&R.stdout&&(u=typeof R.stdout=="string"?R.stdout:""),R.exitCode!==0&&!u){let k=typeof R.stderr=="string"?R.stderr:"",C=R,_;return C.timedOut?_=`Claude Code timed out after ${Math.round(p/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:C.signal?_=k.trim()||`Claude Code killed by signal ${C.signal}`:C.code==="ENOENT"||/ENOENT|spawn claude/i.test((C.shortMessage||"")+" "+k)?_=
|
|
15
|
-
`);m=A.pop()||"";for(let H of A)if(H.trim())try{let q=JSON.parse(H);if(o)try{o(q)}catch{}g=mt(q)||g,y
|
|
14
|
+
`,u))}});let R=await P,E=L.end();if(E&&($+=E),I)return{content:"",error:S||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&R.stdout&&(u=typeof R.stdout=="string"?R.stdout:""),R.exitCode!==0&&!u){let k=typeof R.stderr=="string"?R.stderr:"",C=R,_;return C.timedOut?_=`Claude Code timed out after ${Math.round(p/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:C.signal?_=k.trim()||`Claude Code killed by signal ${C.signal}`:C.code==="ENOENT"||/ENOENT|spawn claude/i.test((C.shortMessage||"")+" "+k)?_=Cn():_=k.trim()||`Claude Code exited with code ${C.exitCode??"unknown"}`,{content:"",...K(_),duration:Date.now()-a}}return w?{content:"",...K(w),duration:Date.now()-a,usage:g,contextTokens:b,numTurns:x,billedModel:l,claudeSessionId:y}:{content:u,duration:Date.now()-a,usage:g,contextTokens:b,numTurns:x,billedModel:l,claudeSessionId:y}}catch(p){return{content:u||"",...K(p.message),duration:Date.now()-a,usage:g,contextTokens:b,numTurns:x,billedModel:l,claudeSessionId:y}}}async function Gs(r,e,t,n){let s=Date.now(),o=ae(r,e,t),i=Tn(Be(Sn(),"agentx-codex-")),a=Be(i,"last-message.txt"),c=An(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:ft(r,e),extendEnv:!1,stdin:"ignore"}),l=Hs(u.stdout);if(u.exitCode!==0||l.apiError){let y=u,b;return y.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:y.signal?b=u.stderr.trim()||`Codex CLI killed by signal ${y.signal}`:y.code==="ENOENT"||/ENOENT|spawn codex/i.test((y.shortMessage||"")+" "+u.stderr)?b=qe():b=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${y.exitCode??"unknown"}`,{content:"",...K(b),duration:Date.now()-s,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||n}}let g="";try{g=kn(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||"")?qe():d?.message;return{content:"",...K(u||"Codex CLI failed"),duration:Date.now()-s}}finally{In(i,{recursive:!0,force:!0})}}async function Js(r,e,t,n,s,o){let i=Date.now(),a=ae(r,e,n),c=Tn(Be(Sn(),"agentx-codex-")),d=Be(c,"last-message.txt"),u=An(r,a,!0,e.model,e.systemPromptAppend,d,s),l="",g,y,b,x;try{let w=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),p=Ge("codex",u,{cwd:r.workspace,timeout:w,reject:!1,env:ft(r,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||r.model,resumeSessionId:s})}catch{}let m="",P="",I=!1,S=new ke("utf8"),$=new ke("utf8"),L=Math.min(w,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),R,E=()=>{R&&clearTimeout(R),R=setTimeout(()=>{I=!0,p.kill("SIGTERM",{forceKillAfterTimeout:5e3})},L)};E(),p.stderr?.on("data",D=>{E(),P+=$.write(D),P.length>16e3&&(P=P.slice(-16e3))}),p.stdout?.on("data",D=>{E(),m+=S.write(D);let A=m.split(`
|
|
15
|
+
`);m=A.pop()||"";for(let H of A)if(H.trim())try{let q=JSON.parse(H);if(o)try{o(q)}catch{}g=mt(q)||g,y=Mn(q)||y,b=ht(q)||b,x=Rn(q)||x;let O=js(q);if(O&&O!==l){let G=O.startsWith(l)?O.slice(l.length):O;l=O.startsWith(l)?O:l+O,G&&t(G,l)}}catch{l+=H+`
|
|
16
16
|
`,t(H+`
|
|
17
|
-
`,l)}});let k=await p;R&&clearTimeout(R);let C=S.end();C&&(m+=C);let _=$.end();if(_&&(P+=_),k.exitCode!==0&&!l||x){let D=P||(typeof k.stderr=="string"?k.stderr:""),A=k,H;return I?H=`Codex CLI produced no output for ${Math.round(L/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.`:A.timedOut?H=`Codex CLI timed out after ${Math.round(w/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:x?H=x:A.signal?H=D.trim()||`Codex CLI killed by signal ${A.signal}`:A.code==="ENOENT"||/ENOENT|spawn codex/i.test((A.shortMessage||"")+" "+D)?H=qe():H=D.trim()||`Codex CLI exited with code ${A.exitCode??"unknown"}`,{content:"",...K(H),duration:Date.now()-i,usage:g,billedModel:y,codexSessionId:b||s}}let T="";try{T=
|
|
17
|
+
`,l)}});let k=await p;R&&clearTimeout(R);let C=S.end();C&&(m+=C);let _=$.end();if(_&&(P+=_),k.exitCode!==0&&!l||x){let D=P||(typeof k.stderr=="string"?k.stderr:""),A=k,H;return I?H=`Codex CLI produced no output for ${Math.round(L/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.`:A.timedOut?H=`Codex CLI timed out after ${Math.round(w/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:x?H=x:A.signal?H=D.trim()||`Codex CLI killed by signal ${A.signal}`:A.code==="ENOENT"||/ENOENT|spawn codex/i.test((A.shortMessage||"")+" "+D)?H=qe():H=D.trim()||`Codex CLI exited with code ${A.exitCode??"unknown"}`,{content:"",...K(H),duration:Date.now()-i,usage:g,billedModel:y,codexSessionId:b||s}}let T="";try{T=kn(d,"utf8").trim()}catch{}if(T&&T!==l){let D=T.startsWith(l)?T.slice(l.length):T;l=T,D&&t(D,l)}return{content:l,duration:Date.now()-i,usage:g,billedModel:y,codexSessionId:b||s}}catch(w){let p=/ENOENT|spawn codex/i.test(w?.message||"")?qe():w?.message;return{content:l,...K(p||"Codex CLI failed"),duration:Date.now()-i,usage:g,billedModel:y,codexSessionId:b||s}}finally{In(c,{recursive:!0,force:!0})}}async function zs(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=Es(r,d,e.model,e.systemPromptAppend,s),l="",g,y=s,b;try{let x=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),w=Ge("opencode",u,{cwd:r.workspace,timeout:x,reject:!1,env:Ls(r,e),extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||r.model,resumeSessionId:s})}catch{}let p=!1,m,P=()=>{p=!0,m=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{w.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",P,{once:!0});let I="",S="",$=new ke("utf8"),L=new ke("utf8"),R=k=>{if(k.trim())try{let C=JSON.parse(k);try{o?.(C)}catch{}typeof C.sessionID=="string"&&(y=C.sessionID);let _=C.type==="text"&&typeof C.part?.text=="string"?C.part.text:void 0;_&&(l+=_,t?.(_,l));let T=C.type==="reasoning"&&typeof C.part?.text=="string"?C.part.text:void 0;T&&a?.(T);let D=C.type==="step_finish"?C.part?.tokens:void 0;D&&(g={inputTokens:se(D.input),outputTokens:se(D.output),cacheReadTokens:se(D.cache?.read),cacheCreateTokens:se(D.cache?.write)}),b=Ns(C)||b}catch{l+=k+`
|
|
18
18
|
`,t?.(k+`
|
|
19
19
|
`,l)}};w.stdout?.on("data",k=>{I+=$.write(k);let C=I.split(`
|
|
20
|
-
`);I=C.pop()||"";for(let _ of C)R(_)}),w.stderr?.on("data",k=>{S+=L.write(k)});let E=await w;if(i&&i.removeEventListener("abort",P),I+=$.end(),I.trim()&&R(I),S+=L.end(),p)return{content:"",error:m||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:y};if(E.exitCode!==0||b){let k=E,C;return k.timedOut?C=`OpenCode timed out after ${Math.round(x/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:b?C=b:k.code==="ENOENT"||/ENOENT|spawn opencode/i.test((k.shortMessage||"")+" "+S)?C=
|
|
20
|
+
`);I=C.pop()||"";for(let _ of C)R(_)}),w.stderr?.on("data",k=>{S+=L.write(k)});let E=await w;if(i&&i.removeEventListener("abort",P),I+=$.end(),I.trim()&&R(I),S+=L.end(),p)return{content:"",error:m||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:y};if(E.exitCode!==0||b){let k=E,C;return k.timedOut?C=`OpenCode timed out after ${Math.round(x/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:b?C=b:k.code==="ENOENT"||/ENOENT|spawn opencode/i.test((k.shortMessage||"")+" "+S)?C=bn():C=S.trim()||`OpenCode exited with code ${k.exitCode??"unknown"}`,{content:"",...K(C),duration:Date.now()-c,usage:g,opencodeSessionId:y}}return{content:l.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||r.model,opencodeSessionId:y}}catch(x){let w=/ENOENT|spawn opencode/i.test(x?.message||"")?bn():x?.message;return{content:l,...K(w||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:y}}}async function Qs(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 Ys(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,y=()=>{let w=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(w))}catch{}};a&&(a.aborted?y():a.addEventListener("abort",y,{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 x=()=>({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 w=r.provider||"claude-code",p=n?`${n}
|
|
21
21
|
|
|
22
|
-
${e.message}`:e.message,m=e.context?.sender,P=typeof m=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(m),I=e.context?.channel==="web-chat"&&P?{userId:m,agentId:e.agentId||"acme-public"}:void 0,S=zt(r),$=Object.keys(S).length>0,L={task:p,cwd:r.workspace,provider:w,model:e.model||r.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:I,providerOpts:o,abortSignal:l.signal,mcpServers:$?S:void 0};if(s){let{generateStream:_}=await import("./agent-V2CA4TXD.js"),T="",D,A,H,q;for await(let O of _(L)){if(c)try{c(O)}catch{}if(O.type==="text_delta")T+=O.text,s(O.text,T);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!==T){let G=O.result.content.slice(T.length);G?(T=O.result.content,s(G,T)):T=O.result.content}D=O.result.tokensUsed,O.result.inputTokens!=null&&(A=O.result.inputTokens),O.result.outputTokens!=null&&(H=O.result.outputTokens)}else if(O.type==="done"){if(O.result.content&&O.result.content!==T){let G=O.result.content.slice(T.length);G?(T=O.result.content,s(G,T)):T=O.result.content}O.result.tokensUsed!=null&&(D=O.result.tokensUsed)}else O.type==="error"&&(q=O.error)}return q&&!T?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}:((A===void 0||H===void 0)&&D&&(A=Math.round(D*.7),H=D-A),{content:T||"Done.",tokensUsed:D,usage:A!==void 0||H!==void 0?{inputTokens:A||0,outputTokens:H||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:R}=await import("./agent-V2CA4TXD.js"),E=await R(L),k=E.inputTokens,C=E.outputTokens;if((k===void 0||C===void 0)&&E.tokensUsed){let _=E.tokensUsed;k=Math.round(_*.7),C=_-k}return{content:E.content||"Done.",tokensUsed:E.tokensUsed,usage:k!==void 0||C!==void 0?{inputTokens:k||0,outputTokens:C||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",y)}}async function Qs(r,e,t,n,s,o){let i=Ke();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 E=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>E}catch(E){return E instanceof ge,null}g&&yt(e.agentId,r,e.model,n,"persistent");let y=ae(r,e,t),b="",x,w,p,m,P,I,S,$=!1,L=()=>{$=!0,i.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?L():o.addEventListener("abort",L,{once:!0}));let R=!1;try{for await(let E of l.runTurn({message:y,taskId:e.taskId??"unknown"})){if(R=!0,s)try{s(E.raw)}catch{}if(E.type==="assistant"){let k=E.raw.message?.content??[];for(let _ of k)_.type==="text"&&typeof _.text=="string"&&(b=_.text);let C=E.raw.message?.usage;if(C){let _=(C.input_tokens||0)+(C.cache_read_input_tokens||0)+(C.cache_creation_input_tokens||0);_>0&&(m=_)}}if(E.type==="result"){let k=E.raw;if(k.is_error){let C=K(typeof k.result=="string"?k.result:"claude error");x=C.error,w=C.errorKind}else typeof k.result=="string"&&k.result.length>0&&(b=k.result);typeof k.session_id=="string"&&(S=k.session_id),k.usage&&(p={inputTokens:k.usage.input_tokens||0,outputTokens:k.usage.output_tokens||0,cacheReadTokens:k.usage.cache_read_input_tokens||0,cacheCreateTokens:k.usage.cache_creation_input_tokens||0}),typeof k.num_turns=="number"&&(P=k.num_turns),typeof k.message?.model=="string"?I=k.message.model:typeof k.model=="string"&&(I=k.model)}}}catch(E){if($)x="task cancelled by operator",w="cancelled";else if(R){let k=K(`persistent claude process error: ${E?.message||String(E)}`);x=k.error,w=k.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${E?.message||E}); falling back to spawn-per-task`),i.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",L),null}finally{o&&o.removeEventListener("abort",L)}return $&&!x&&(x="task cancelled by operator",w="cancelled"),{content:$?"":b,error:x,errorKind:w,duration:Date.now()-a,usage:p,contextTokens:m,numTurns:P,billedModel:I,claudeSessionId:S}}async function Mn(r,e,t,n,s,o,i,a,c){switch(r.tier){case"claude-code":if(r.persistentProcess){let d=await Qs(r,e,s,o,i,a);if(d!==null)return d}return n?Ks(r,e,n,s,o,i,a):Ws(r,e,s,o,a);case"codex-cli":return n?qs(r,e,n,s,o,i):Bs(r,e,s,o);case"opencode":return Gs(r,e,n,s,o,i,a,c);case"sdk":{let d=r.provider||"claude",u=t[d]?.apiKey;return u?Js(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 zs(r,e,l,s,n,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${r.tier}`}}}import{readFileSync as pe,writeFileSync as Rn,mkdirSync as Ys,existsSync as bt,readdirSync as xt}from"fs";import{resolve as fe}from"path";var wt=12e3,Ie=30,Xs=720,Zs=40,Vs=18e4,er="[Compacted conversation summary",tr=7*864e5,nr=[/\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 sr(r){return r?nr.some(e=>e.test(r)):!1}var rr=[{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 Dn(r){if(!r)return null;let e=0;for(let t of rr)t.re.test(r)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Pn(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 _n(r,e){let t=(r??[]).filter(o=>o.role==="user"),n=t[t.length-1];return n?(n.content===e?t[t.length-2]:n)?.content??null:null}function On(r,e,t){if(t<=0)return[];let n=(r??[]).filter(i=>i.role==="user"),s=n[n.length-1],o=(s&&s.content===e?n.length-1:n.length)-1;return o<=0?[]:n.slice(Math.max(0,o-t),o).map(i=>i.content)}function or(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 Je=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=fe(e,".agentx/sessions"),bt(this.sessionsDir)||Ys(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Xs),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??Zs),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Vs)}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:wt});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 fe(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(bt(o))try{let d=JSON.parse(pe(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(!bt(i))return null;try{return JSON.parse(pe(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,s,o){let i=this.getSession(e,t,n);Pn(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);Pn(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??wt),c=[],d=0;for(let g=o.messages.length-1;g>=0&&c.length<i;g--){let y=o.messages[g];if(d+=y.content.length,c.push(y),d>=a)break}c.reverse();let u=[`[Conversation history for today (${o.day})]`],l="";for(let g of c){let y=or(g.timestamp);y!==l&&(u.push(`\u2014 ${y} \u2014`),l=y);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=xt(this.sessionsDir).filter(I=>I.startsWith(`${a}:`)&&I.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(I=>{let S=I.match(l);if(!S)return!1;let $=S[1];return $>=d&&$<=u}),y=[],b=0,x=e.query?.toLowerCase(),w=e.participants?.length?new Set(e.participants):void 0;for(let I of g){let S;try{S=JSON.parse(pe(fe(this.sessionsDir,I),"utf-8"))}catch{continue}if(S.agentId===e.agentId&&!(e.channel&&S.channel!==e.channel)&&!(e.chatId&&S.chatId!==e.chatId))for(let $ of S.messages)b++,!(!$.timestamp||$.timestamp<o||$.timestamp>=i)&&(w&&$.role==="user"&&!w.has($.name??"")||x&&!$.content.toLowerCase().includes(x)||y.push({ts:$.timestamp,role:$.role,senderName:$.name??"",content:$.content,channel:S.channel,chatId:S.chatId,day:S.day,sessionFile:I}))}y.sort((I,S)=>S.ts.localeCompare(I.ts));let p=y.slice(0,t),m=p.length>0?p[p.length-1].ts:null,P=y.length>t;return{turns:p,oldestTs:m,hasMore:P,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=xt(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(pe(fe(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let y of g.messages)!y.timestamp||y.timestamp<n||c.push({ts:y.timestamp,role:y.role,senderName:y.name??"",content:y.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)}sessionIdleMs(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?null:Date.now()-new Date(s.updatedAt).getTime()}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!==""&&!
|
|
22
|
+
${e.message}`:e.message,m=e.context?.sender,P=typeof m=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(m),I=e.context?.channel==="web-chat"&&P?{userId:m,agentId:e.agentId||"acme-public"}:void 0,S=Yt(r),$=Object.keys(S).length>0,L={task:p,cwd:r.workspace,provider:w,model:e.model||r.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:I,providerOpts:o,abortSignal:l.signal,mcpServers:$?S:void 0};if(s){let{generateStream:_}=await import("./agent-2U574KBZ.js"),T="",D,A,H,q;for await(let O of _(L)){if(c)try{c(O)}catch{}if(O.type==="text_delta")T+=O.text,s(O.text,T);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!==T){let G=O.result.content.slice(T.length);G?(T=O.result.content,s(G,T)):T=O.result.content}D=O.result.tokensUsed,O.result.inputTokens!=null&&(A=O.result.inputTokens),O.result.outputTokens!=null&&(H=O.result.outputTokens)}else if(O.type==="done"){if(O.result.content&&O.result.content!==T){let G=O.result.content.slice(T.length);G?(T=O.result.content,s(G,T)):T=O.result.content}O.result.tokensUsed!=null&&(D=O.result.tokensUsed)}else O.type==="error"&&(q=O.error)}return q&&!T?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}:((A===void 0||H===void 0)&&D&&(A=Math.round(D*.7),H=D-A),{content:T||"Done.",tokensUsed:D,usage:A!==void 0||H!==void 0?{inputTokens:A||0,outputTokens:H||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:R}=await import("./agent-2U574KBZ.js"),E=await R(L),k=E.inputTokens,C=E.outputTokens;if((k===void 0||C===void 0)&&E.tokensUsed){let _=E.tokensUsed;k=Math.round(_*.7),C=_-k}return{content:E.content||"Done.",tokensUsed:E.tokensUsed,usage:k!==void 0||C!==void 0?{inputTokens:k||0,outputTokens:C||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",y)}}async function Xs(r,e,t,n,s,o){let i=Ke();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 E=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>E}catch(E){return E instanceof ge,null}g&&yt(e.agentId,r,e.model,n,"persistent");let y=ae(r,e,t),b="",x,w,p,m,P,I,S,$=!1,L=()=>{$=!0,i.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?L():o.addEventListener("abort",L,{once:!0}));let R=!1;try{for await(let E of l.runTurn({message:y,taskId:e.taskId??"unknown"})){if(R=!0,s)try{s(E.raw)}catch{}if(E.type==="assistant"){let k=E.raw.message?.content??[];for(let _ of k)_.type==="text"&&typeof _.text=="string"&&(b=_.text);let C=E.raw.message?.usage;if(C){let _=(C.input_tokens||0)+(C.cache_read_input_tokens||0)+(C.cache_creation_input_tokens||0);_>0&&(m=_)}}if(E.type==="result"){let k=E.raw;if(k.is_error){let C=K(typeof k.result=="string"?k.result:"claude error");x=C.error,w=C.errorKind}else typeof k.result=="string"&&k.result.length>0&&(b=k.result);typeof k.session_id=="string"&&(S=k.session_id),k.usage&&(p={inputTokens:k.usage.input_tokens||0,outputTokens:k.usage.output_tokens||0,cacheReadTokens:k.usage.cache_read_input_tokens||0,cacheCreateTokens:k.usage.cache_creation_input_tokens||0}),typeof k.num_turns=="number"&&(P=k.num_turns),typeof k.message?.model=="string"?I=k.message.model:typeof k.model=="string"&&(I=k.model)}}}catch(E){if($)x="task cancelled by operator",w="cancelled";else if(R){let k=K(`persistent claude process error: ${E?.message||String(E)}`);x=k.error,w=k.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${E?.message||E}); falling back to spawn-per-task`),i.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",L),null}finally{o&&o.removeEventListener("abort",L)}return $&&!x&&(x="task cancelled by operator",w="cancelled"),{content:$?"":b,error:x,errorKind:w,duration:Date.now()-a,usage:p,contextTokens:m,numTurns:P,billedModel:I,claudeSessionId:S}}async function Pn(r,e,t,n,s,o,i,a,c){switch(r.tier){case"claude-code":if(r.persistentProcess){let d=await Xs(r,e,s,o,i,a);if(d!==null)return d}return n?qs(r,e,n,s,o,i,a):Bs(r,e,s,o,a);case"codex-cli":return n?Js(r,e,n,s,o,i):Gs(r,e,s,o);case"opencode":return zs(r,e,n,s,o,i,a,c);case"sdk":{let d=r.provider||"claude",u=t[d]?.apiKey;return u?Qs(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 Ys(r,e,l,s,n,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${r.tier}`}}}import{readFileSync as pe,writeFileSync as Dn,mkdirSync as Zs,existsSync as bt,readdirSync as xt}from"fs";import{resolve as fe}from"path";var wt=12e3,Ie=30,Vs=720,er=40,tr=18e4,nr="[Compacted conversation summary",sr=7*864e5,rr=[/\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 or(r){return r?rr.some(e=>e.test(r)):!1}var ir=[{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 On(r){if(!r)return null;let e=0;for(let t of ir)t.re.test(r)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function _n(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 En(r,e){let t=(r??[]).filter(o=>o.role==="user"),n=t[t.length-1];return n?(n.content===e?t[t.length-2]:n)?.content??null:null}function Nn(r,e,t){if(t<=0)return[];let n=(r??[]).filter(i=>i.role==="user"),s=n[n.length-1],o=(s&&s.content===e?n.length-1:n.length)-1;return o<=0?[]:n.slice(Math.max(0,o-t),o).map(i=>i.content)}function ar(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 Je=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=fe(e,".agentx/sessions"),bt(this.sessionsDir)||Zs(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Vs),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??er),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??tr)}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:wt});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 fe(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(bt(o))try{let d=JSON.parse(pe(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(!bt(i))return null;try{return JSON.parse(pe(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,s,o){let i=this.getSession(e,t,n);_n(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);_n(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??wt),c=[],d=0;for(let g=o.messages.length-1;g>=0&&c.length<i;g--){let y=o.messages[g];if(d+=y.content.length,c.push(y),d>=a)break}c.reverse();let u=[`[Conversation history for today (${o.day})]`],l="";for(let g of c){let y=ar(g.timestamp);y!==l&&(u.push(`\u2014 ${y} \u2014`),l=y);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=xt(this.sessionsDir).filter(I=>I.startsWith(`${a}:`)&&I.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(I=>{let S=I.match(l);if(!S)return!1;let $=S[1];return $>=d&&$<=u}),y=[],b=0,x=e.query?.toLowerCase(),w=e.participants?.length?new Set(e.participants):void 0;for(let I of g){let S;try{S=JSON.parse(pe(fe(this.sessionsDir,I),"utf-8"))}catch{continue}if(S.agentId===e.agentId&&!(e.channel&&S.channel!==e.channel)&&!(e.chatId&&S.chatId!==e.chatId))for(let $ of S.messages)b++,!(!$.timestamp||$.timestamp<o||$.timestamp>=i)&&(w&&$.role==="user"&&!w.has($.name??"")||x&&!$.content.toLowerCase().includes(x)||y.push({ts:$.timestamp,role:$.role,senderName:$.name??"",content:$.content,channel:S.channel,chatId:S.chatId,day:S.day,sessionFile:I}))}y.sort((I,S)=>S.ts.localeCompare(I.ts));let p=y.slice(0,t),m=p.length>0?p[p.length-1].ts:null,P=y.length>t;return{turns:p,oldestTs:m,hasMore:P,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=xt(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(pe(fe(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let y of g.messages)!y.timestamp||y.timestamp<n||c.push({ts:y.timestamp,role:y.role,senderName:y.name??"",content:y.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)}sessionIdleMs(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?null:Date.now()-new Date(s.updatedAt).getTime()}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!==""&&!or(s))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=xt(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(pe(fe(this.sessionsDir,d),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),y=!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 ${y} (${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-FD4R23HZ.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(er)}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 fe(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(pe(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()},Rn(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>tr?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>wt&&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);Rn(t,JSON.stringify(e,null,2))}catch{}}};var ir=new Set(["cron","a2a","workflow","selftest"]),ar=[[/^User:\s*You are\s/i,"role brief"],[/^User:\s*(Run|Execute)\s/i,"run instruction"],[/^User:\s*\[MISSED RUN/i,"missed cron run"],[/^User:\s*(\[[^\]]{0,40}\]:?\s*)?\[Recent group conversation\]/i,"group chat dump"]];function En(r){if(r.responseLength<=50)return{capture:!1,reason:"response too short"};let t=(r.channel??"").toLowerCase().split("@")[0];if(ir.has(t))return{capture:!1,reason:`machine channel: ${t}`};let n=r.content.slice(0,400);for(let[s,o]of ar)if(s.test(n))return{capture:!1,reason:o};return{capture:!0}}var ze=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 Nn,appendFileSync as cr,existsSync as me,mkdirSync as dr}from"fs";import{resolve as he}from"path";var Ln={"claude-fable":{input:10,output:50,cacheRead:1,cacheCreate:12.5},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-8":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-7":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"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-5":{input:2,output:10,cacheRead:.2,cacheCreate:2.5},"claude-sonnet":{input:3,output:15,cacheRead:.3,cacheCreate:3.75},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheCreate:1.25}},jn=2e5,ur=1.5;function lr(r){let e=r.toLowerCase(),t=(...n)=>n.some(s=>e.includes(s));return t("fable","mythos")?"claude-fable":e.includes("opus")?t("opus-5","opus5","opus-5-")?"claude-opus-5":t("4-8","4.8")?"claude-opus-4-8":t("4-7","4.7")?"claude-opus-4-7":t("4-6","4.6")?"claude-opus-4-6":t("4-5","4.5")?"claude-opus-4-5":t("4-1","4.1","opus-3","opus3","-3-")?"claude-opus":"claude-opus-5":e.includes("haiku")?"claude-haiku":t("sonnet-5","sonnet5")?"claude-sonnet-5":"claude-sonnet"}function Hn(r){return r.inputTokens+r.cacheReadTokens+r.cacheCreateTokens>jn?{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 Fn=500,gr=".agentx/pricing/custom.json",ye=class{dir;cache=null;pricing;constructor(e=he(process.cwd(),".agentx/usage")){this.dir=e,dr(this.dir,{recursive:!0}),this.pricing=pr()}getPricing(){return this.pricing}static calculateCost(e,t,n=Ln){let s=lr(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*ur}cost(e,t){return ye.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,y=0,b=0,x=0,w=0,p=0,m=0,P=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>jn?(w=n.inputTokens,p=n.outputTokens,m=n.cacheReadTokens,P=n.cacheCreateTokens):(g=n.inputTokens,y=n.outputTokens,b=n.cacheReadTokens,x=n.cacheCreateTokens):s!==void 0&&o!==void 0&&(g=Math.ceil(s/4),y=Math.ceil(o/4)),l.inputTokens+=g,l.outputTokens+=y,l.cacheReadTokens+=b,l.cacheCreateTokens+=x,l.tier2InputTokens=(l.tier2InputTokens||0)+w,l.tier2OutputTokens=(l.tier2OutputTokens||0)+p,l.tier2CacheReadTokens=(l.tier2CacheReadTokens||0)+m,l.tier2CacheCreateTokens=(l.tier2CacheCreateTokens||0)+P,i&&l.errors++,l.byChannel||(l.byChannel={});let I=(c||"other").toLowerCase(),S=l.byChannel[I]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};S.tasks++,S.totalDuration+=t,S.inputTokens+=g,S.outputTokens+=y,S.cacheReadTokens+=b,S.cacheCreateTokens+=x,S.tier2InputTokens+=w,S.tier2OutputTokens+=p,S.tier2CacheReadTokens+=m,S.tier2CacheCreateTokens+=P,i&&S.errors++,l.byChannel[I]=S,d&&(l.sessionKeys||(l.sessionKeys=[]),l.sessionKeys.includes(d)||(l.sessionKeys.push(d),l.sessionKeys.length>Fn&&l.sessionKeys.splice(0,l.sessionKeys.length-Fn))),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={},y={},b={};for(let[x,w]of Object.entries(n.agents)){let p=this.cost(w);g[x]=p,s+=w.tasks,o+=(w.inputTokens||0)+(w.tier2InputTokens||0),i+=(w.outputTokens||0)+(w.tier2OutputTokens||0),a+=(w.cacheReadTokens||0)+(w.tier2CacheReadTokens||0),c+=(w.cacheCreateTokens||0)+(w.tier2CacheCreateTokens||0),d+=p,p>l&&(l=p,u=x);let m=w.sessionKeys?.length||0;y[x]={sessions:m,avgTasksPerSession:m>0?w.tasks/m:w.tasks};for(let[P,I]of Object.entries(w.byChannel||{})){let S=this.cost(I,w.model);b[P]=(b[P]||0)+S}}return{date:t,totalTasks:s,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:u,topCost:l,agentCosts:g,agentSessionStats:y,byChannel:b}}appendToTokenCosts(e,t){let n=t||he(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)?cr(n,c+`
|
|
27
|
-
`):
|
|
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-FD4R23HZ.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(nr)}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 fe(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(pe(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()},Dn(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>sr?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>wt&&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);Dn(t,JSON.stringify(e,null,2))}catch{}}};var cr=new Set(["cron","a2a","workflow","selftest"]),dr=[[/^User:\s*You are\s/i,"role brief"],[/^User:\s*(Run|Execute)\s/i,"run instruction"],[/^User:\s*\[MISSED RUN/i,"missed cron run"],[/^User:\s*(\[[^\]]{0,40}\]:?\s*)?\[Recent group conversation\]/i,"group chat dump"]];function Fn(r){if(r.responseLength<=50)return{capture:!1,reason:"response too short"};let t=(r.channel??"").toLowerCase().split("@")[0];if(cr.has(t))return{capture:!1,reason:`machine channel: ${t}`};let n=r.content.slice(0,400);for(let[s,o]of dr)if(s.test(n))return{capture:!1,reason:o};return{capture:!0}}var ze=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 Ln,appendFileSync as ur,existsSync as me,mkdirSync as lr}from"fs";import{resolve as he}from"path";var Hn={"claude-fable":{input:10,output:50,cacheRead:1,cacheCreate:12.5},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-8":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-7":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"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-5":{input:2,output:10,cacheRead:.2,cacheCreate:2.5},"claude-sonnet":{input:3,output:15,cacheRead:.3,cacheCreate:3.75},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheCreate:1.25}},Un=2e5,gr=1.5;function pr(r){let e=r.toLowerCase(),t=(...n)=>n.some(s=>e.includes(s));return t("fable","mythos")?"claude-fable":e.includes("opus")?t("opus-5","opus5","opus-5-")?"claude-opus-5":t("4-8","4.8")?"claude-opus-4-8":t("4-7","4.7")?"claude-opus-4-7":t("4-6","4.6")?"claude-opus-4-6":t("4-5","4.5")?"claude-opus-4-5":t("4-1","4.1","opus-3","opus3","-3-")?"claude-opus":"claude-opus-5":e.includes("haiku")?"claude-haiku":t("sonnet-5","sonnet5")?"claude-sonnet-5":"claude-sonnet"}function Wn(r){return r.inputTokens+r.cacheReadTokens+r.cacheCreateTokens>Un?{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 jn=500,fr=".agentx/pricing/custom.json",ye=class{dir;cache=null;pricing;constructor(e=he(process.cwd(),".agentx/usage")){this.dir=e,lr(this.dir,{recursive:!0}),this.pricing=mr()}getPricing(){return this.pricing}static calculateCost(e,t,n=Hn){let s=pr(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*gr}cost(e,t){return ye.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,y=0,b=0,x=0,w=0,p=0,m=0,P=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>Un?(w=n.inputTokens,p=n.outputTokens,m=n.cacheReadTokens,P=n.cacheCreateTokens):(g=n.inputTokens,y=n.outputTokens,b=n.cacheReadTokens,x=n.cacheCreateTokens):s!==void 0&&o!==void 0&&(g=Math.ceil(s/4),y=Math.ceil(o/4)),l.inputTokens+=g,l.outputTokens+=y,l.cacheReadTokens+=b,l.cacheCreateTokens+=x,l.tier2InputTokens=(l.tier2InputTokens||0)+w,l.tier2OutputTokens=(l.tier2OutputTokens||0)+p,l.tier2CacheReadTokens=(l.tier2CacheReadTokens||0)+m,l.tier2CacheCreateTokens=(l.tier2CacheCreateTokens||0)+P,i&&l.errors++,l.byChannel||(l.byChannel={});let I=(c||"other").toLowerCase(),S=l.byChannel[I]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};S.tasks++,S.totalDuration+=t,S.inputTokens+=g,S.outputTokens+=y,S.cacheReadTokens+=b,S.cacheCreateTokens+=x,S.tier2InputTokens+=w,S.tier2OutputTokens+=p,S.tier2CacheReadTokens+=m,S.tier2CacheCreateTokens+=P,i&&S.errors++,l.byChannel[I]=S,d&&(l.sessionKeys||(l.sessionKeys=[]),l.sessionKeys.includes(d)||(l.sessionKeys.push(d),l.sessionKeys.length>jn&&l.sessionKeys.splice(0,l.sessionKeys.length-jn))),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={},y={},b={};for(let[x,w]of Object.entries(n.agents)){let p=this.cost(w);g[x]=p,s+=w.tasks,o+=(w.inputTokens||0)+(w.tier2InputTokens||0),i+=(w.outputTokens||0)+(w.tier2OutputTokens||0),a+=(w.cacheReadTokens||0)+(w.tier2CacheReadTokens||0),c+=(w.cacheCreateTokens||0)+(w.tier2CacheCreateTokens||0),d+=p,p>l&&(l=p,u=x);let m=w.sessionKeys?.length||0;y[x]={sessions:m,avgTasksPerSession:m>0?w.tasks/m:w.tasks};for(let[P,I]of Object.entries(w.byChannel||{})){let S=this.cost(I,w.model);b[P]=(b[P]||0)+S}}return{date:t,totalTasks:s,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:u,topCost:l,agentCosts:g,agentSessionStats:y,byChannel:b}}appendToTokenCosts(e,t){let n=t||he(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)?ur(n,c+`
|
|
27
|
+
`):Ln(n,`# Token Costs
|
|
28
28
|
|
|
29
29
|
Daily token cost tracking. Auto-appended at midnight (Africa/Tunis).
|
|
30
30
|
Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
@@ -32,25 +32,25 @@ 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||he(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||he(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 x=new Date(Date.now()-b*864e5).toISOString().slice(0,10),w=this.getDate(x);if(w)for(let[p,m]of Object.entries(w.agents)){let P=this.cost(m);t+=m.tasks;let I=(m.inputTokens||0)+(m.tier2InputTokens||0),S=(m.outputTokens||0)+(m.tier2OutputTokens||0),$=(m.cacheReadTokens||0)+(m.tier2CacheReadTokens||0),L=(m.cacheCreateTokens||0)+(m.tier2CacheCreateTokens||0);n+=I,s+=S,o+=$,i+=L,a+=m.errors,c+=P;let R=d[p]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};R.tasks+=m.tasks,R.input+=I,R.output+=S,R.cacheRead+=$,R.cacheCreate+=L,R.total=R.input+R.output+R.cacheRead+R.cacheCreate,R.totalDuration+=m.totalDuration,R.avgDuration=R.totalDuration/R.tasks,R.cost+=P,R.sessions+=m.sessionKeys?.length||0,m.model&&(R.model=m.model),d[p]=R;for(let[E,k]of Object.entries(m.byChannel||{})){let C=this.cost(k,m.model),_=u[E]||{tasks:0,cost:0};_.tasks+=k.tasks,_.cost+=C,u[E]=_}}}let l=n+s+o+i,g=o+i>0?o/(o+i):0,y={};for(let[b,x]of Object.entries(d))y[b]={sessions:x.sessions,avgTasksPerSession:x.sessions>0?x.tasks/x.sessions:x.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:y}}filePath(e){return he(this.dir,`${e}.json`)}save(e){try{
|
|
35
|
+
`)}hasTokenCostsEntry(e,t){let n=t||he(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||he(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 x=new Date(Date.now()-b*864e5).toISOString().slice(0,10),w=this.getDate(x);if(w)for(let[p,m]of Object.entries(w.agents)){let P=this.cost(m);t+=m.tasks;let I=(m.inputTokens||0)+(m.tier2InputTokens||0),S=(m.outputTokens||0)+(m.tier2OutputTokens||0),$=(m.cacheReadTokens||0)+(m.tier2CacheReadTokens||0),L=(m.cacheCreateTokens||0)+(m.tier2CacheCreateTokens||0);n+=I,s+=S,o+=$,i+=L,a+=m.errors,c+=P;let R=d[p]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};R.tasks+=m.tasks,R.input+=I,R.output+=S,R.cacheRead+=$,R.cacheCreate+=L,R.total=R.input+R.output+R.cacheRead+R.cacheCreate,R.totalDuration+=m.totalDuration,R.avgDuration=R.totalDuration/R.tasks,R.cost+=P,R.sessions+=m.sessionKeys?.length||0,m.model&&(R.model=m.model),d[p]=R;for(let[E,k]of Object.entries(m.byChannel||{})){let C=this.cost(k,m.model),_=u[E]||{tasks:0,cost:0};_.tasks+=k.tasks,_.cost+=C,u[E]=_}}}let l=n+s+o+i,g=o+i>0?o/(o+i):0,y={};for(let[b,x]of Object.entries(d))y[b]={sessions:x.sessions,avgTasksPerSession:x.sessions>0?x.tasks/x.sessions:x.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:y}}filePath(e){return he(this.dir,`${e}.json`)}save(e){try{Ln(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function mr(){let r=JSON.parse(JSON.stringify(Hn));try{let e=he(process.cwd(),fr);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 hr={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,memory:400,history:1200,"cross-chat":800,wiki:2500}},Kn=4;function Bn(r,e=hr){let t=yr(r,e);t.sort((i,a)=>i.priority-a.priority);let n=[],s=0,o=e.totalBudget*Kn;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Kn,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
|
-
`)}function
|
|
37
|
+
`)}function yr(r,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(br(r,t("channel",200))),n.push(xr(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(`
|
|
39
39
|
`);i.push(d)}r.intent.leaf?.input&&i.push(` input: ${r.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
|
|
40
|
-
`),tags:["intent",...r.intent.path]})}else{let i=
|
|
40
|
+
`),tags:["intent",...r.intent.path]})}else{let i=wr(r.message);i.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let s=[];r.replyToText&&s.push(`[Replying to]: ${r.replyToText.slice(0,300)}`),r.mediaPath&&(s.push(`[Attached file: ${r.mediaPath}]`),s.push(`[File type: ${r.mediaType||"unknown"}]`),r.mediaType?.startsWith("image/")?s.push("Please view this image and respond to it."):r.mediaType?.startsWith("audio/")&&s.push("Please transcribe this audio and respond.")),r.issueMR&&s.push(`[${r.issueMR.type} #${r.issueMR.iid}: ${r.issueMR.title}]`),s.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:s.join(`
|
|
41
41
|
`),tags:["artifacts",...r.mediaType?["media"]:[]]}),r.skillInjection&&n.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:r.skillInjection,tags:["skills","auto-inject"]}),r.patternContext&&n.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:r.patternContext,tags:["patterns","behavioral","self-improving"]}),r.procedureContext&&n.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:r.procedureContext,tags:["procedures","sop"]}),r.memoryContext&&n.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:r.memoryContext,tags:["memory","persistent"]});let o=r.groupHistory||r.sessionHistory;if(o&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"]}),r.crossChatContext&&n.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:r.crossChatContext,tags:["history","cross-chat"]}),r.longMemoryRecall&&n.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:r.longMemoryRecall,tags:["history","long-memory"]}),r.handoverNote){let i=[`[Handover] You are taking over this conversation from ${r.handoverNote.fromAgent}.`];r.handoverNote.summary&&i.push(`Operator summary: ${r.handoverNote.summary}`),i.push(`Handover time: ${r.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
|
|
42
42
|
`),tags:["handover",r.handoverNote.fromAgent]})}return r.rotationMemo&&n.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${r.rotationMemo.reason}, ${r.rotationMemo.capturedAt}). Carry on from these facts; do not claim you lack prior context:]`,r.rotationMemo.memo].join(`
|
|
43
|
-
`),tags:["continuity","rotation-memo"]}),r.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:r.wikiContext,tags:["wiki","knowledge"]}),n}function
|
|
44
|
-
`),tags:s,rules:n}}function
|
|
45
|
-
`),tags:n}}function
|
|
46
|
-
`)}getAll(e){let t=this.filePath(e);if(!
|
|
43
|
+
`),tags:["continuity","rotation-memo"]}),r.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:r.wikiContext,tags:["wiki","knowledge"]}),n}function br(r,e){let t=[`Channel: ${r.channel}`];r.chatId&&t.push(`Chat ID: ${r.chatId} (use this verbatim in /recall, /send)`);let n=[],s=[r.channel];switch(r.channel){case"telegram":r.agentHandle&&t.push(`Your handle: ${r.agentHandle}`),t.push(`From: ${r.sender}`),r.senderId&&t.push(`Telegram user ID: ${r.senderId}`),r.senderUsername&&t.push(`Username: @${r.senderUsername}`),n.push("Format responses using Telegram-compatible markdown"),n.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),n.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${r.sender}`),n.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),n.push("No rich formatting \u2014 plain text only"),n.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${r.sender}`),n.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),n.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),n.push("Do NOT delegate to other agents"),n.push("Reference issues with #IID and merge requests with !IID"),n.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),n.push("Never narrate what you are about to do \u2014 just do it and report the result"),s.push("code-review");break;case"discord":t.push(`From: ${r.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:r.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),s.push("webhook","automated"))}return n.length&&(t.push(""),t.push("[Rules]"),t.push(...n.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
44
|
+
`),tags:s,rules:n}}function xr(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
|
+
`),tags:n}}function wr(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 Tr,writeFileSync as qn,appendFileSync as kr,mkdirSync as Ir,existsSync as Gn}from"fs";import{resolve as Tt}from"path";var Jn=200,Sr=7,Qe=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=Tt(e,".agentx/memory"),Gn(this.memoryDir)||Ir(this.memoryDir,{recursive:!0})}filePath(e){return Tt(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()};kr(this.filePath(e),JSON.stringify(n)+`
|
|
46
|
+
`)}getAll(e){let t=this.filePath(e);if(!Gn(t))return[];try{return Tr(t,"utf-8").split(`
|
|
47
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(y=>`${y.keywords.join(" ")} ${y.content}`),i=Tt(this.memoryDir,`${t}_bm25_cache.json`),a=Le(o,i),c=Fe(e,a),d=new Map(c.map(y=>[y.docIndex,y.score])),l=s.map((y,b)=>{let x=d.get(b)??0;return y.category==="secret"&&(x+=2),y.category==="commitment"&&(x+=1),{memory:y,score:x}}).filter(y=>y.score>0);if(l.length===0)return s.slice(-n);let g=l.sort((y,b)=>b.score-y.score).slice(0,n).map(y=>y.memory);if(g.length>0)try{this.recordAccess(t,g.map(y=>y.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
|
-
`)}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&&
|
|
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&&qn(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(`
|
|
51
|
-
`)}hasSimilar(e,t){let n=this.getAll(e),o=t.toLowerCase().split(/\s+/).filter(i=>i.length>3);return n.some(i=>{let a=i.content.toLowerCase();return o.filter(d=>a.includes(d)).length>=o.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let n=Date.now(),s=
|
|
51
|
+
`)}hasSimilar(e,t){let n=this.getAll(e),o=t.toLowerCase().split(/\s+/).filter(i=>i.length>3);return n.some(i=>{let a=i.content.toLowerCase();return o.filter(d=>a.includes(d)).length>=o.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let n=Date.now(),s=Sr*24*60*60*1e3;t=t.filter(i=>i.category==="task-state"&&i.expiresAt?new Date(i.expiresAt).getTime()>n:i.category==="task-state"&&!i.expiresAt?n-new Date(i.createdAt).getTime()<s:!0),t.length>Jn&&(t=t.slice(-Jn));let o=this.filePath(e);qn(o,t.map(i=>JSON.stringify(i)).join(`
|
|
52
52
|
`)+`
|
|
53
|
-
`)}};import{existsSync as Ce,mkdirSync as
|
|
53
|
+
`)}};import{existsSync as Ce,mkdirSync as Cr,readdirSync as vr,readFileSync as $r,unlinkSync as kt,writeFileSync as Ye}from"fs";import{resolve as re}from"path";var ce=["user","feedback","project","reference"],Xe=class{baseDir;constructor(e={}){let t=e.baseDir??re(process.cwd(),".agentx");this.baseDir=re(t,"agent-memory")}dirFor(e){let t=St(e),n=re(this.baseDir,t);return Cr(n,{recursive:!0}),n}fileFor(e,t,n){return re(this.dirFor(e),`${t}_${St(n)}.md`)}indexPath(e){return re(this.dirFor(e),"MEMORY.md")}save(e){if(!ce.includes(e.type))throw new Error(`invalid memory type: ${e.type}`);if(!e.name.trim())throw new Error("memory name is required");if(!e.description.trim())throw new Error("memory description is required");let t=this.fileFor(e.agentId,e.type,e.name),n=new Date().toISOString(),s=n,o=ve(t);if(o){let a=It(o);a&&(s=a.createdAt)}let i={name:St(e.name),type:e.type,description:e.description.trim(),body:e.body.trimEnd(),createdAt:s,updatedAt:n};return Ye(t,Ar(i)),this.rewriteIndex(e.agentId),i}get(e,t){for(let n of ce){let s=this.fileFor(e,n,t);if(!Ce(s))continue;let o=It(ve(s)??"");if(o)return o}return null}list(e){let t=this.dirFor(e);if(!Ce(t))return[];let n=[];for(let s of vr(t,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name==="MEMORY.md")continue;let o=It(ve(re(t,s.name))??"");o&&n.push(o)}return n.sort((s,o)=>{let i=ce.indexOf(s.type),a=ce.indexOf(o.type);return i!==a?i-a:s.name.localeCompare(o.name)})}remove(e,t){let n=!1;for(let s of ce){let o=this.fileFor(e,s,t);Ce(o)&&(kt(o),n=!0)}return n&&this.rewriteIndex(e),n}indexMarkdown(e){let t=this.indexPath(e);return ve(t)??""}syncToWorkspace(e,t){if(!t)return;let n=this.indexMarkdown(e).trim(),s=re(t,".agentx-memory.md");n?Ye(s,n+`
|
|
54
54
|
`):Ce(s)&&kt(s);let o=re(t,"CLAUDE.md"),i="<!-- AGENTX-MEMORY-START \u2014 auto-managed by agentx; edit via `agentx memory` -->",a="<!-- AGENTX-MEMORY-END -->",c=n?`${i}
|
|
55
55
|
${n}
|
|
56
56
|
${a}`:"",d=ve(o)??"",u=d.indexOf(i),l=d.indexOf(a),g;if(u>=0&&l>u){let y=d.slice(0,u).replace(/\n+$/,""),b=d.slice(l+a.length).replace(/^\n+/,"");g=c?[y,c,b].filter(Boolean).join(`
|
|
@@ -63,15 +63,15 @@ ${a}`:"",d=ve(o)??"",u=d.indexOf(i),l=d.indexOf(a),g;if(u>=0&&l>u){let y=d.slice
|
|
|
63
63
|
|
|
64
64
|
`+c+`
|
|
65
65
|
`:c+`
|
|
66
|
-
`;else return;Ye(o,g)}rewriteIndex(e){let t=this.list(e);if(t.length===0){let o=this.indexPath(e);Ce(o)&&kt(o);return}let n={user:[],feedback:[],project:[],reference:[]};for(let o of t)n[o.type].push(o);let s=[];s.push(`# Memory \u2014 ${e}`,""),s.push("This is the agent's experiential memory: user preferences,"),s.push("feedback, project-specific context, and external references."),s.push("Updated via `agentx memory` CLI or by the agent itself.");for(let o of ce){let i=n[o];if(i.length){s.push("",`## ${
|
|
67
|
-
`))}};function
|
|
66
|
+
`;else return;Ye(o,g)}rewriteIndex(e){let t=this.list(e);if(t.length===0){let o=this.indexPath(e);Ce(o)&&kt(o);return}let n={user:[],feedback:[],project:[],reference:[]};for(let o of t)n[o.type].push(o);let s=[];s.push(`# Memory \u2014 ${e}`,""),s.push("This is the agent's experiential memory: user preferences,"),s.push("feedback, project-specific context, and external references."),s.push("Updated via `agentx memory` CLI or by the agent itself.");for(let o of ce){let i=n[o];if(i.length){s.push("",`## ${Pr(o)}`,"");for(let a of i)s.push(`- **${a.name}** \u2014 ${a.description} _(updated ${a.updatedAt.slice(0,10)})_`)}}s.push(""),Ye(this.indexPath(e),s.join(`
|
|
67
|
+
`))}};function Ar(r){return["---",`name: ${r.name}`,`description: ${Mr(r.description)}`,`type: ${r.type}`,`created: ${r.createdAt}`,`updated: ${r.updatedAt}`,"---",""].join(`
|
|
68
68
|
`)+r.body+`
|
|
69
69
|
`}function It(r){if(!r.startsWith(`---
|
|
70
70
|
`))return null;let e=r.indexOf(`
|
|
71
71
|
---
|
|
72
72
|
`,4);if(e<0)return null;let t=r.slice(4,e),n=r.slice(e+5).replace(/^\n+/,"").trimEnd(),s={};for(let o of t.split(`
|
|
73
|
-
`)){let i=o.indexOf(":");if(i<0)continue;let a=o.slice(0,i).trim(),c=
|
|
74
|
-
`),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext};return s.onFlush&&await s.onFlush([a]),[a]}case"followup":return s.onFlush&&await s.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let s=this.key(e,t,n);this.queues.delete(s)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as
|
|
73
|
+
`)){let i=o.indexOf(":");if(i<0)continue;let a=o.slice(0,i).trim(),c=Rr(o.slice(i+1).trim());s[a]=c}return!s.name||!s.type||!s.description||!ce.includes(s.type)?null:{name:s.name,type:s.type,description:s.description,body:n,createdAt:s.created??"",updatedAt:s.updated??s.created??""}}function Mr(r){return/[:#\n]/.test(r)?`"${r.replace(/"/g,'\\"')}"`:r}function Rr(r){return r.startsWith('"')&&r.endsWith('"')&&r.length>=2?r.slice(1,-1).replace(/\\"/g,'"'):r}function St(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"unnamed"}function Pr(r){return r.charAt(0).toUpperCase()+r.slice(1)}function ve(r){try{return $r(r,"utf-8")}catch{return null}}var Ze=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,n){return`${e}:${t}:${n}`}getOrCreate(e,t,n){let s=this.key(e,t,n);return this.queues.has(s)||this.queues.set(s,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(s)}setMode(e,t,n,s){this.getOrCreate(e,t,n).mode=s}onFlush(e,t,n,s){this.getOrCreate(e,t,n).onFlush=s}isBusy(e,t,n){return this.getOrCreate(e,t,n).running}markRunning(e,t,n){let s=this.getOrCreate(e,t,n);return s.running?!1:(s.running=!0,!0)}enqueue(e,t,n,s){let o=this.getOrCreate(e,t,n);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(s),o.mode}}async markDone(e,t,n){let s=this.getOrCreate(e,t,n);if(s.running=!1,s.pending.length===0)return[];let o=[...s.pending];switch(s.pending=[],s.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
|
|
74
|
+
`),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext};return s.onFlush&&await s.onFlush([a]),[a]}case"followup":return s.onFlush&&await s.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let s=this.key(e,t,n);this.queues.delete(s)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as Dr,writeFileSync as zn,appendFileSync as _r,mkdirSync as Or,existsSync as Qn}from"fs";import{resolve as Ct}from"path";var Yn=50,Er="claude-haiku-4-20250514",Nr=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
|
|
75
75
|
|
|
76
76
|
Extract patterns like:
|
|
77
77
|
- "When asked about X, the approach that works is Y"
|
|
@@ -87,19 +87,19 @@ SKIP:
|
|
|
87
87
|
Output a JSON array:
|
|
88
88
|
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
89
89
|
|
|
90
|
-
If nothing worth extracting, output: []`,Ve=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Ct(e,".agentx/patterns"),
|
|
91
|
-
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};
|
|
90
|
+
If nothing worth extracting, output: []`,Ve=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Ct(e,".agentx/patterns"),Qn(this.patternsDir)||Or(this.patternsDir,{recursive:!0})}filePath(e){return Ct(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!Qn(t))return[];try{return Dr(t,"utf-8").split(`
|
|
91
|
+
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};_r(this.filePath(e),JSON.stringify(n)+`
|
|
92
92
|
`)}findRelevant(e,t,n=5){let s=this.getAll(t);if(s.length===0)return[];let o=s.map(u=>`${u.context} ${u.pattern}`),i=Ct(this.patternsDir,`${t}_bm25_cache.json`),a=Le(o,i),d=Fe(e,a).slice(0,n).map(u=>s[u.docIndex]).filter(u=>u.confidence>=.3);return d.length>0&&this.recordAccess(t,d.map(u=>u.id)),d}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let n of e)t.push(`- ${n.pattern} (context: ${n.context}, confidence: ${Math.round(n.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
|
|
93
|
-
`)}hasSimilar(e,t){let n=this.getAll(e),s=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return s.filter(c=>i.includes(c)).length>=s.length*.6})}recordAccess(e,t){let n=this.getAll(e),s=new Set(t),o=!1;for(let i of n)s.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&
|
|
93
|
+
`)}hasSimilar(e,t){let n=this.getAll(e),s=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return s.filter(c=>i.includes(c)).length>=s.length*.6})}recordAccess(e,t){let n=this.getAll(e),s=new Set(t),o=!1;for(let i of n)s.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&zn(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
94
94
|
`)+`
|
|
95
|
-
`)}prune(e){let t=this.getAll(e);t.length<=
|
|
95
|
+
`)}prune(e){let t=this.getAll(e);t.length<=Yn||(t.sort((n,s)=>s.confidence*s.accessCount-n.confidence*n.accessCount),t=t.slice(0,Yn),zn(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
96
96
|
`)+`
|
|
97
|
-
`))}};async function
|
|
97
|
+
`))}};async function Xn(r,e,t,n,s){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-KO2DODIO.js"),c=(await o("claude").generate([{role:"system",content:Nr},{role:"user",content:`User: ${e.slice(0,500)}
|
|
98
98
|
|
|
99
|
-
Agent: ${t.slice(0,1e3)}`}],{model:
|
|
100
|
-
\u2026[truncated ${r.length-e} chars]`}var Mt;function
|
|
99
|
+
Agent: ${t.slice(0,1e3)}`}],{model:Er,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let d=JSON.parse(c[0]);if(!(!Array.isArray(d)||d.length===0)){for(let u of d)s.hasSimilar(r,u.pattern)||s.addPattern(r,{agentId:r,pattern:u.pattern,context:u.context,confidence:u.confidence||.5,source:n});Math.random()<.05&&s.prune(r)}}import{EventEmitter as Fr}from"events";var $t=class{inner=new Fr;constructor(){this.inner.setMaxListeners(50)}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){return this.inner.emit(e,t)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this}},vt;function ee(){return vt||(vt=new $t),vt}Jt();Jt();var Zn=["manual","notify","auto"];function Lr(r){return typeof r=="string"&&Zn.includes(r)}var At={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var $e=class{sessions=new Map;items=new Map;waiters=new Map;opts;constructor(e={}){this.opts={...At,...e}}options(){return this.opts}register(e,t={}){let n=t.now??Date.now(),s=this.sessions.get(e);if(s)return s.lastSeenAt=n,t.cwd&&(s.cwd=t.cwd),t.model&&(s.model=t.model),s;let o={sessionId:e,cwd:t.cwd??"",agentIds:[],mode:"notify",lastSeenAt:n,registeredAt:n,model:t.model,drainedThisTurn:0};return this.sessions.set(e,o),o}touch(e,t=Date.now()){let n=this.sessions.get(e);return n&&(n.lastSeenAt=t),n}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,n){let s=this.sessions.get(e);if(s){for(let o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));return s.agentIds.includes(t)||s.agentIds.push(t),n&&(s.mode=n),s}}unbind(e,t){let n=this.sessions.get(e);if(n)return n.agentIds=t?n.agentIds.filter(s=>s!==t):[],n}setMode(e,t){let n=this.sessions.get(e);if(n)return n.mode=t,n}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now()){this.sessions.delete(e);for(let n of this.items.values())n.sessionId===e&&(n.state==="pending"||n.state==="claimed")&&this.settle(n,"expired",t,"session ended")}offer(e,t=Date.now()){let n=this.sessionFor(e.agentId);if(!n)return null;if(t-n.lastSeenAt>this.opts.staleSessionMs)return this.deregister(n.sessionId,t),null;let s={id:je(t),agentId:e.agentId,sessionId:n.sessionId,state:"pending",text:jr(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(s.id,s),new Promise(o=>{this.waiters.set(s.id,{resolve:o})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,n)=>t.createdAt-n.createdAt)}pendingCount(e){let t=0;for(let n of this.items.values())n.sessionId===e&&n.state==="pending"&&t++;return t}claim(e,t=Date.now()){let n=this.sessions.get(e);if(!n||n.awaitingAnswer)return;let s=this.pending(e)[0];if(!(!s||s.state!=="pending"))return s.state="claimed",s.claimedAt=t,n.awaitingAnswer=s.id,n.lastSeenAt=t,n.drainedThisTurn++,s}answer(e,t,n=Date.now()){let s=this.sessions.get(e);if(!s?.awaitingAnswer)return;let o=this.items.get(s.awaitingAnswer);if(s.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",n),o}release(e,t=Date.now()){let n=this.sessions.get(e);if(!n?.awaitingAnswer)return;let s=this.items.get(n.awaitingAnswer);if(n.awaitingAnswer=void 0,!(!s||s.state!=="claimed"))return s.state="pending",s.claimedAt=void 0,n.lastSeenAt=t,s}expire(e,t,n=Date.now()){let s=this.items.get(e);if(!s||s.state!=="pending"&&s.state!=="claimed")return!1;let o=this.sessions.get(s.sessionId);return o?.awaitingAnswer===s.id&&(o.awaitingAnswer=void 0),this.settle(s,"expired",n,t),!0}sweep(e=Date.now()){let t=0;for(let n of this.items.values())n.state==="pending"&&e-n.createdAt>=this.opts.claimTimeoutMs?this.expire(n.id,"not claimed in time",e)&&t++:n.state==="claimed"&&e-(n.claimedAt??n.createdAt)>=this.opts.claimTimeoutMs&&this.expire(n.id,"claimed but never answered",e)&&t++;for(let n of this.sessions.values())e-n.lastSeenAt>this.opts.staleSessionMs&&this.deregister(n.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let n=0;for(let[s,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(s),n++);return n}settle(e,t,n,s){e.state=t,e.settledAt=n;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:s??"expired"}))}};function jr(r,e){return r.length<=e?r:`${r.slice(0,e)}
|
|
100
|
+
\u2026[truncated ${r.length-e} chars]`}var Mt;function Vn(){return Mt||(Mt=new $e),Mt}import{readFileSync as Hr}from"fs";import{homedir as Ur}from"os";import{join as Wr}from"path";var Ae=null,Kr=6e4;function Br(){try{let r=Wr(Ur(),".claude.json"),e=Hr(r,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function qr(r,e=Date.now()){if(!r)return{available:!0,checkedAt:e,unknown:!0};let t=typeof r.cachedExtraUsageDisabledReason=="string"?r.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function Gr(r=!1){let e=Date.now();return!r&&Ae&&e-Ae.checkedAt<Kr||(Ae=qr(Br(),e)),Ae}function es(r){let e=Gr();return e.available||r?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var ts={warnRatio:.8},B={...ts},Jr=5*60*60*1e3,zr=60*60*1e3,de=[];function ns(r){B={...ts,...r||{}}}function ss(r){let e=r-Jr,t=0;for(;t<de.length&&de[t]<e;)t++;t>0&&de.splice(0,t)}function rs(r=Date.now()){ss(r),de.push(r)}function os(r=Date.now()){ss(r);let e=r-zr,t=0;for(let o=de.length-1;o>=0&&de[o]>=e;o--)t++;let n=de.length,s={lastHour:t,last5h:n,maxPerHour:B.maxPerHour,maxPer5h:B.maxPer5h};return B.maxPerHour&&B.maxPerHour>0&&(s.hourlyRatio=t/B.maxPerHour),B.maxPer5h&&B.maxPer5h>0&&(s.fiveHourRatio=n/B.maxPer5h),s}function is(r,e=Date.now()){let t=os(e);return r?null:B.maxPerHour&&t.lastHour>=B.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${B.maxPerHour} in the last hour. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPerHour in DaemonConfig if this is a false positive.`,usage:t}:B.maxPer5h&&t.last5h>=B.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${B.maxPer5h} in the last 5h. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPer5h in DaemonConfig if this is a false positive.`,usage:t}:null}function as(r=Date.now()){let e=os(r),t=B.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=t&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=t&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of cap)`:null}var Rt=new Map;function cs(r,e,t){return t?`${r}:${e}:${t}`:`${r}:${e}`}function ds(r,e,t,n=Date.now()){let s=Rt.get(r);s||(s={key:r,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},Rt.set(r,s)),s.samples+=1,s.baseline=.2*e+(1-.2)*s.baseline,s.current=e,s.peak=Math.max(s.peak,e),s.lastAt=n,s.ring.push({key:r,timestamp:n,total:e,parts:t}),s.ring.length>100&&s.ring.shift()}function us(r){let e=Rt.get(r);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let n=e.current/e.baseline;return`prompt-size drift for ${r}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as Y,mkdirSync as fo,readdirSync as te,readFileSync as Re,rmSync as mo,writeFileSync as ho}from"fs";import{resolve as j}from"path";import{existsSync as le,mkdirSync as Pt,readFileSync as Qr,readdirSync as Yr,renameSync as Xr,unlinkSync as Zr,writeFileSync as et}from"fs";import{resolve as oe,relative as tt}from"path";import{z as W}from"zod";var ue=W.object({id:W.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:W.string().min(1),trigger:W.string().min(1,"procedures must describe when they apply"),inputs:W.array(W.string()).default([]),expected:W.string().optional(),kpis:W.array(W.string()).default([]),owner:W.string().optional(),tags:W.array(W.string()).default([]),status:W.enum(["draft","active","deprecated"]).default("active"),source:W.string().optional(),evidence:W.array(W.string()).default([]),created:W.string().optional(),updated:W.string().optional(),related:W.array(W.string()).default([])});function Vr(r){let e=r.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:r};let t={};for(let n of e[1].split(`
|
|
101
101
|
`)){let s=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!s)continue;let o=s[1],i=s[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{t[o]=JSON.parse(i);continue}catch{}t[o]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),t[o]=i}return{meta:t,body:e[2]}}function nt(r){let e=["---"];return e.push(`id: ${r.id}`),e.push(`title: "${r.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${r.trigger.replace(/"/g,'\\"')}"`),r.inputs?.length&&e.push(`inputs: ${JSON.stringify(r.inputs)}`),r.expected&&e.push(`expected: "${r.expected.replace(/"/g,'\\"')}"`),r.kpis?.length&&e.push(`kpis: ${JSON.stringify(r.kpis)}`),r.owner&&e.push(`owner: ${r.owner}`),r.tags?.length&&e.push(`tags: ${JSON.stringify(r.tags)}`),e.push(`status: ${r.status}`),r.source&&e.push(`source: "${r.source.replace(/"/g,'\\"')}"`),r.evidence?.length&&e.push(`evidence: ${JSON.stringify(r.evidence)}`),r.related?.length&&e.push(`related: ${JSON.stringify(r.related)}`),r.created&&e.push(`created: ${r.created}`),r.updated&&e.push(`updated: ${r.updated}`),e.push("---"),e.join(`
|
|
102
|
-
`)}var Me=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??oe(process.cwd(),".agentx/procedures"),Pt(this.baseDir,{recursive:!0})}pathFor(e){return oe(this.baseDir,`${e}.md`)}get draftsDir(){return oe(this.baseDir,"_drafts")}draftPathFor(e){return oe(this.draftsDir,`${e}.md`)}parseFile(e){let t=
|
|
102
|
+
`)}var Me=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??oe(process.cwd(),".agentx/procedures"),Pt(this.baseDir,{recursive:!0})}pathFor(e){return oe(this.baseDir,`${e}.md`)}get draftsDir(){return oe(this.baseDir,"_drafts")}draftPathFor(e){return oe(this.draftsDir,`${e}.md`)}parseFile(e){let t=Qr(e,"utf-8"),{meta:n,body:s}=Vr(t),o=ue.safeParse({...n,inputs:n.inputs||[],kpis:n.kpis||[],tags:n.tags||[],related:n.related||[],evidence:n.evidence||[]});return o.success?{meta:o.data,body:s.trim(),path:tt(this.baseDir,e)}:null}listDir(e){if(!le(e))return[];let t=[];for(let n of Yr(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".md")||n.name.startsWith("_"))continue;let s=this.parseFile(oe(e,n.name));s&&t.push(s)}return t.sort((n,s)=>n.meta.id.localeCompare(s.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return le(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return le(t)?this.parseFile(t):null}add(e,t){let n=ue.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),s=this.pathFor(n.id);if(le(s))throw new Error(`Procedure already exists: ${n.id}`);return et(s,nt(n)+`
|
|
103
103
|
|
|
104
104
|
`+t.trim()+`
|
|
105
105
|
`),{meta:n,body:t.trim(),path:tt(this.baseDir,s)}}update(e,t,n){let s=this.get(e);if(!s)throw new Error(`Procedure not found: ${e}`);let o=ue.parse({...s.meta,...t,id:s.meta.id,updated:new Date().toISOString().slice(0,10)}),i=n!==void 0?n:s.body;return et(this.pathFor(e),nt(o)+`
|
|
@@ -111,14 +111,14 @@ Agent: ${t.slice(0,1e3)}`}],{model:_r,maxTokens:512})).content.trim().match(/\[[
|
|
|
111
111
|
`),{meta:n,body:t.trim(),path:tt(this.baseDir,s)}}promoteDraft(e){let t=this.getDraft(e);if(!t)throw new Error(`Draft not found: ${e}`);if(this.get(e))throw new Error(`Procedure already exists: ${e}`);let n=ue.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return et(this.pathFor(e),nt(n)+`
|
|
112
112
|
|
|
113
113
|
`+t.body+`
|
|
114
|
-
`),
|
|
115
|
-
`)}function
|
|
114
|
+
`),Zr(this.draftPathFor(e)),{meta:n,body:t.body,path:tt(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!le(t))throw new Error(`Draft not found: ${e}`);let n=oe(this.draftsDir,"_rejected");Pt(n,{recursive:!0}),Xr(t,oe(n,`${e}.md`))}isRejected(e){return le(oe(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as eo,mkdirSync as to,readFileSync as no,writeFileSync as so}from"fs";import{dirname as ro,resolve as oo}from"path";import{z as J}from"zod";var io=J.object({key:J.string(),count:J.number().int().min(0).default(0),firstSeen:J.string(),lastSeen:J.string(),taskIds:J.array(J.string()).default([]),sampleMessage:J.string().default(""),status:J.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:J.string().optional()}),ao=J.object({minedThrough:J.string().optional(),candidates:J.array(io).default([])});function ls(r){return oo(r,"_candidates.json")}function co(r){let e=ls(r);if(!eo(e))return{candidates:[]};try{let t=ao.safeParse(JSON.parse(no(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function uo(r,e){let t=ls(r);to(ro(t),{recursive:!0}),so(t,JSON.stringify(e,null,2)+`
|
|
115
|
+
`)}function lo(r,e,t,n,s){let o=r.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:n,lastSeen:n,taskIds:[],sampleMessage:s,status:"counting"},r.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,n<o.firstSeen&&(o.firstSeen=n),n>o.lastSeen&&(o.lastSeen=n),o.sampleMessage||(o.sampleMessage=s)),o}function go(r,e){return r.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function po(r,e,t,n){let s=r.candidates.find(o=>o.key===e);s&&(s.status=t,n&&(s.procedureId=n))}function Dt(r){return new Set(r.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function gs(r,e){if(r.size===0||e.size===0)return 0;let t=0;for(let n of r)e.has(n)&&t++;return t/Math.max(r.size,e.size)}function _t(r,e,t={}){let n=Math.max(1,t.limit??3),s=t.minScore??.2,o=Dt(r),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=gs(o,Dt(a.meta.trigger));d>0&&c.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),l=gs(o,Dt(u));l>0&&c.push("title/tags");let g=Math.min(1,d*.7+l*.5);g>=s&&i.push({procedure:a,score:g,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,n)}function Ot(r){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...r.map(t=>{let n=t.procedure,s=[`[Known procedure: ${n.meta.title}]`,n.meta.trigger];return n.meta.inputs.length&&s.push(`Inputs: ${n.meta.inputs.join(", ")}`),s.push(n.body),n.meta.expected&&s.push(`Done when: ${n.meta.expected}`),s.push(`(details: agentx procedure show ${n.meta.id})`),s.join(`
|
|
116
116
|
`)})].join(`
|
|
117
117
|
|
|
118
|
-
`)}function
|
|
118
|
+
`)}function ps(r,e){return e!=="claude-code"&&e!=="codex-cli"?!1:r==="github"||r==="gitlab"}var xs;function Ca(r){xs=r}function va(){return xs}var fs=64*1024,yo=5*60*1e3,be=".agentx/task-history",bo=30;function Pe(r,e=800){return r.length<=e?r:r.slice(0,e)+` \u2026[+${r.length-e} chars]`}function xo(r,e){let t={};return r?.path?.length&&(t.intentPath=r.path,t.intentPathLabel=r.pathLabel),e?.sender&&(t.sender=e.sender),e?.senderId&&(t.senderId=e.senderId),e?.senderUsername&&(t.senderUsername=e.senderUsername),e?.group&&e?.sender&&(t.group=e.group),Object.keys(t).length>0?t:void 0}function wo(r,e,t={}){let n;try{n=r.listArticles(e)}catch{return""}if(n.length===0)return"";let s=new Map;for(let u of n){let l=u.meta.type||"untyped",g=s.get(l)||[];g.push(u.meta.title),s.set(l,g)}let o=t.maxArticles??400,i=n.length<=o,a=Array.from(s.entries()).sort().map(([u,l])=>i?`**${u}** (${l.length}) \u2014 ${l.sort().join(" \xB7 ")}`:`**${u}** \u2014 ${l.length} article${l.length===1?"":"s"}`).join(`
|
|
119
119
|
`),c=process.argv[1]||"dist/cli.js",d=r.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 the single source of truth]",`${n.length} article${n.length===1?"":"s"}. This is long-term memory for the whole fleet: who people are, what systems exist, what happened, what was decided, how we do things.`,"","It outranks every other context you are given. Your workspace memory, injected skills, mined procedures and behavioural patterns are all either staged into the wiki or derived from it \u2014 where any of them disagrees with the wiki, the wiki is right and the other is stale.","","Catalog:",a,"",`For the contents of an article, or any question spanning several, run:
|
|
120
120
|
node ${c} wiki query "the question" --dir ${d} --agent ${e}`,"","It walks the catalog and the wikilink graph and returns a cited answer. Ask it before you grep the workspace or answer from your own recollection.","[End Institutional Wiki]"].join(`
|
|
121
|
-
`)}var Et=8*1024;function
|
|
121
|
+
`)}var Et=8*1024;function ms(r){if(r.length<=Et)return r;let e=r.length-Et;return r.slice(0,Et)+`\u2026[+${e}]`}function hs(r,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let n of t){if(n?.type!=="tool_use")continue;let s=typeof n.name=="string"?n.name:"";s&&r.set(s,(r.get(s)??0)+1)}}function To(r,e){if(!r||r.length===0)return null;for(let t of r)if((e.get(t)??0)===0)return t;return null}function ys(r,e,t){if(!t||typeof t!="object")return;let n=t.type,s=new Date().toISOString(),o=ee();if(n==="assistant"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_use"){let a=i.input!=null?JSON.stringify(i.input):"";o.emit("task:step",{taskId:r,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?ms(a):null,at:s})}return}if(n==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:r,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?ms(a):null,at:s})}return}}function ko(){let r="",e="";return t=>{if(!t||typeof t!="object")return"";let n=t.type;if(n==="codex.spawned"){let s=t.model?` model=${t.model}`:"",o=t.resumeSessionId?` resume=${String(t.resumeSessionId).slice(0,8)}`:"";return`. codex started${s}${o}
|
|
122
122
|
`}if(n==="thread.started")return`. codex thread started${t.thread_id?` thread=${String(t.thread_id).slice(0,8)}`:""}
|
|
123
123
|
`;if(n==="turn.started")return`. codex turn started
|
|
124
124
|
`;if(n==="turn.completed"){let s=t.usage||{},o=s.input_tokens??s.inputTokens,i=s.output_tokens??s.outputTokens;return`. codex turn completed${o||i?` input=${o||0} output=${i||0}`:""}
|
|
@@ -133,25 +133,25 @@ Agent: ${t.slice(0,1e3)}`}],{model:_r,maxTokens:512})).content.trim().match(/\[[
|
|
|
133
133
|
\u2192 ${i}(${a})
|
|
134
134
|
`}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)}
|
|
135
135
|
`}return s}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
136
|
-
`:""}}var
|
|
137
|
-
`)[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";
|
|
138
|
-
`).length}L`,X=`[${e.agentId}] ${p}:${m} ${U} | session.messages=${f.length}`+(f.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",X)}catch(h){ie.cat("context",`[${e.agentId}] context-diag error: ${h?.message??h}`)}let Ft;if(i.def.contextReferences&&!A)try{let h=i.def.workspace,f=this.referencesCache.get(h);if(!f){let[N,U]=await Promise.all([lt(i.def.workspace),gt(i.def.workspace)]);if(N.byId.size===0&&U.recipes.length===0){let[X,v]=await Promise.all([lt(process.cwd()),gt(process.cwd())]);f={refs:X,recipes:v}}else f={refs:N,recipes:U};this.referencesCache.set(h,f)}let M=
|
|
139
|
-
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${De.lookbackDays}d, turns=${h.turns.length}, scanned=${h.totalScanned}`)}}catch(h){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${h.message}`)}let
|
|
140
|
-
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.`:""
|
|
136
|
+
`:""}}var bs=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Xe;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;classifier;graphStore;handoverStore=new tn;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 Je(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new en(void 0,void 0,"unified"),this.memoryStore=new Qe,this.patternStore=new Ve,this.rateLimiter=new ze,this.tokenTracker=new ye,this.messageQueue=new Ze,ns({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Zt({baseDir:j(process.cwd(),e.graph.baseDir),log:(...s)=>t("[graph]",...s)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Vt({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 maybeRotateForContinuity(e,t,n,s,o){let i=null,a=null,c=[];try{let g=this.sessions.getSession(e.agentId,n,s);i=En(g.messages,e.message??""),c=Nn(g.messages,e.message??"",this.config.session.continuityStateTurns),g.updatedAt&&(a=Math.round((Date.now()-Date.parse(g.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,s),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,s)||null,agentId:e.agentId,channel:n},u=await zt(gn,fn(d),pn,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${s}`}],features:{agent:e.agentId,channel:n}});return!u||u.mode!=="active"||!mn(u.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${s} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,n,s,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,s),ee().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:s,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,s,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-7T75BLEX.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(`
|
|
137
|
+
`)[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";an().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=Vn().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 h=await o;if(h.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${h.sessionId}`),{content:h.text,viaAttachedSession:h.sessionId};this.log(`[${e.agentId}] attached session did not take it (${h.reason}) \u2014 spawning`)}let i=this.agents.get(e.agentId);if(!i){if(this.meshFallback){let h=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(M=>M.id===e.agentId));if(h){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${h.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(h.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:h.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${h.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}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 h=Date.now(),f=25*6e4,M=500;for(;i.activeTasks>=i.def.maxConcurrent;){if(Date.now()-h>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(N=>setTimeout(N,M))}}else{let h=i.def.queueMode||"collect",f=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(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let M=this.messageQueue.pendingCount(e.agentId,a,c);return this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${M})`),{content:"",error:`__queued__:${f}:${M}`}}}let d=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(h,f)=>{this.log(`[${e.agentId}] ${h} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/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),message:e.message||"",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 y=h=>{if(h){g.buffer+=h,g.buffer.length>fs&&(g.buffer=g.buffer.slice(g.buffer.length-fs));for(let f of g.subscribers)try{f(h)}catch{}}},b=je();e.taskId=b;let x=new Map,w;if(t){let h=ko();w=f=>{let M=h(f);if(M&&y(M),ys(b,e.agentId,f),hs(x,f),s)try{s(f)}catch{}}}else w=h=>{if(ys(b,e.agentId,h),hs(x,h),s)try{s(h)}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",m=e.context?.chatId||e.context?.group||e.context?.sender||"default",P=e.context?.sender||"User",I=i.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,p,m),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${p}:${m}`),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:m,reason:"stale",at:new Date().toISOString()})),e.freshSession||await this.sessions.seedIfEmpty(e.agentId,p,m),this.sessions.addUserMessage(e.agentId,p,m,P,e.message);let S=Date.now();ee().emit("task:started",{agentId:e.agentId,channel:p,chatId:m,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(S).toISOString(),taskId:b});let $;if(this.classifier&&p!=="a2a"&&!I)try{$=await this.classifier.classify({text:e.message,channel:p,sender:e.context?.sender,agentId:e.agentId})||void 0}catch(h){this.log(`[classifier] classify failed for ${e.agentId}: ${h?.message||h}`)}let L=this.config.workflows?.matching,R;if(this.config.workflows?.enabled&&L?.enabled)try{let h=new un({baseDir:j(process.cwd(),this.config.workflows.dir)}),f=ln({agentId:e.agentId,channel:p,message:e.message,intentPath:$?.path},h.list());f&&f.confidence>=L.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${L.mode} reasons=${f.reasons.join(",")||"n/a"}`),L.mode==="auto"&&f.confidence>=L.autoRunThreshold&&(this.workflowAutoRunner?R={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(h){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${h?.message||h}`)}let E=this.wikiHub.getAgentWiki(e.agentId),k=this.memoryStore.findRelevant(e.message,e.agentId,I?3:8),C=this.memoryStore.buildContext(k),_=this.patternStore.findRelevant(e.message,e.agentId,5),T=this.patternStore.buildContext(_),D="";if(!I)try{let{loadLocalSkills:h,getAutoInjectSkills:f}=await import("./loader-BOKE5M5S.js"),M=await h(i.def.workspace);D=f(M,e.message)}catch{}let A=i.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,p,m):i.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,p,m):i.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,p,m):void 0;if(A&&this.sessions.isSessionStale(e.agentId,p,m)&&(this.log(`[${e.agentId}] session stale for ${p}:${m}, starting fresh`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,A,p,m,"stale"),this.sessions.clearClaudeSessionId(e.agentId,p,m),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:m,reason:"stale",at:new Date().toISOString()}),A=void 0),A&&this.sessions.shouldRotateByTierTwo(e.agentId,p,m)){let h=this.sessions.getLastTurnContextTokens(e.agentId,p,m);this.log(`[${e.agentId}] tier-2 rotation for ${p}:${m} (last turn context: ${h} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,A,p,m,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,p,m),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:m,reason:"tier-2",lastTurnInputTokens:h,at:new Date().toISOString()}),A=void 0}if(A&&this.sessions.shouldRotateByTurns(e.agentId,p,m)){let h=this.sessions.getTurnCount(e.agentId,p,m);this.log(`[${e.agentId}] max-turns rotation for ${p}:${m} (${h} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,A,p,m,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,p,m),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:m,reason:"max-turns",at:new Date().toISOString()}),A=void 0}A&&i.def.tier==="claude-code"&&await this.maybeRotateForContinuity(e,i,p,m,A)&&(A=void 0);try{let h=await this.sessions.compactIfNeeded(e.agentId,p,m,this.memoryStore);if(h.compacted){let f=h.qualityScore??"?",M=h.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${p}:${m} (quality: ${f}%, ${M} entities lost)`),h.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${h.lostEntities.slice(0,5).join(", ")}`),h.drift){let N=h.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(h){this.log(`[${e.agentId}] compaction failed (non-fatal): ${h.message}`)}let H=process.env.AGENTX_CONTEXT_SURGERY==="1",q=I?{maxMessages:8,maxChars:2400}:H&&ps(p,i.def.tier)?{maxMessages:6,maxChars:1800}:void 0,O=!A&&!I?wo(E,e.agentId):void 0,G=A?void 0:this.sessions.buildHistoryContext(e.agentId,p,m,q),ws=A?void 0:this.sessions.getRotationMemo(e.agentId,p,m)??void 0,Nt;if(this.config.procedures?.injection?.enabled&&!A&&!I)try{let h=new Me({baseDir:j(process.cwd(),this.config.procedures.dir)}),f=_t(e.message,h.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){Nt=Ot(f);for(let M of f)this.log(`[${e.agentId}] procedure match ${M.procedure.meta.id} score=${M.score.toFixed(2)} (${M.reasons.join(",")})`)}}catch(h){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${h?.message||h}`)}if(ie&&ie.cat)try{let f=this.sessions.getSession(e.agentId,p,m).messages,M=f[0],N=f[f.length-1],U=G===void 0?`resume=${A?A.slice(0,8):"?"} (no rebuild)`:`fresh history=${G.length}c/${G.split(`
|
|
138
|
+
`).length}L`,X=`[${e.agentId}] ${p}:${m} ${U} | session.messages=${f.length}`+(f.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",X)}catch(h){ie.cat("context",`[${e.agentId}] context-diag error: ${h?.message??h}`)}let Ft;if(i.def.contextReferences&&!A)try{let h=i.def.workspace,f=this.referencesCache.get(h);if(!f){let[N,U]=await Promise.all([lt(i.def.workspace),gt(i.def.workspace)]);if(N.byId.size===0&&U.recipes.length===0){let[X,v]=await Promise.all([lt(process.cwd()),gt(process.cwd())]);f={refs:X,recipes:v}}else f={refs:N,recipes:U};this.referencesCache.set(h,f)}let M=cn({agentId:e.agentId,intentTags:$?.path,message:e.message},f.recipes,f.refs);M.cards.length>0&&(Ft=on(M.cards,500*4)),M.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${M.unresolvedIds.join(", ")}`)}catch(h){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${h?.message||h}`)}let Lt=this.sessions.getCrossSessionSummary(e.agentId,p,m,e.message),jt,De=On(e.message);if(De)try{let h=this.sessions.recallTurns({agentId:e.agentId,channel:p,chatId:m,lookbackDays:De.lookbackDays,limit:12});if(h.turns.length>0){let f=[`[Long-memory recall \u2014 last ${De.lookbackDays}d on this chat (cue-triggered)]`],M=[...h.turns].sort((N,U)=>N.ts.localeCompare(U.ts));for(let N of M){let U=N.ts.slice(11,16)+" "+N.day,X=N.role==="user"?N.senderName||"User":N.senderName||"Agent";f.push(`${U} ${X}: ${N.content}`)}h.hasMore&&f.push(`[\u2026${h.totalScanned-h.turns.length}+ older turns available \u2014 call /recall with before=${h.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),jt=f.join(`
|
|
139
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${De.lookbackDays}d, turns=${h.turns.length}, scanned=${h.totalScanned}`)}}catch(h){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${h.message}`)}let Ts=I?"layered":e.contextStrategy??i.def.contextStrategy??this.config.session.contextStrategy??"layered",Ht,Ut,Wt=!1;if(Ts==="planner"){try{let{planContext:h}=await import("./context-planner-AQHJMVY2.js"),f=await h({agentId:e.agentId,channel:p,chatId:m,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore});f?(Wt=!0,Ht=f.sessionHistory,C=f.memoryContext,Lt=f.crossChatContext,Ut=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(h){this.log(`[${e.agentId}] planner failed (non-fatal): ${h.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Wt&&A&&(this.sessions.clearClaudeSessionId(e.agentId,p,m),A=void 0)}let st=`${e.agentId}:${p}:${m}`,_e=rn(e.message);_e&&(_e==="default"?(this.activeSouls.delete(st),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(st,_e),this.log(`[${e.agentId}] Soul switched to: ${_e}`)));let ks=this.activeSouls.get(st),Is=nn(i.def.workspace,ks),Ss=sn(Is),Cs=this.agentMemory.indexMarkdown(e.agentId),vs=i.def.tier==="claude-code"||i.def.tier==="codex-cli"?`[Operating principle]
|
|
140
|
+
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.`:"",$s=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(`
|
|
141
141
|
`):"",Kt="";if(i.def.workspace){let h=j(i.def.workspace,"CLAUDE.md");if(Y(h))try{let f=Re(h,"utf-8");Kt=`[Project CLAUDE.md]
|
|
142
142
|
${f.length>4e3?f.slice(0,4e3)+`
|
|
143
143
|
|
|
144
144
|
[CLAUDE.md truncated to 4KB]`:f}`}catch{}}let Oe=e.context?.runbookPath,rt=[];if(Oe&&Y(Oe)){let h=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,M=4e3,N=16e3;for(let U of h){if(f>=N)break;let X=j(Oe,U);if(Y(X))try{let v=Re(X,"utf-8"),Q=v.length>M?v.slice(0,M)+`
|
|
145
145
|
|
|
146
146
|
[${U} truncated to ${M} bytes]`:v;rt.push(`[Project Runbook \u2014 ${U} from ${Oe}]
|
|
147
|
-
${Q}`),f+=Q.length}catch{}}}let
|
|
147
|
+
${Q}`),f+=Q.length}catch{}}}let As=rt.length>0?rt.join(`
|
|
148
148
|
|
|
149
|
-
`):"",ot=[i.def.systemPrompt||"",
|
|
149
|
+
`):"",ot=[i.def.systemPrompt||"",vs,$s,Kt,As,Ss||"",Cs||""].filter(h=>h.trim().length>0).join(`
|
|
150
150
|
|
|
151
|
-
`)||void 0
|
|
152
|
-
`),M=!1)},X=h?f:f?(F,z)=>{U(),f(F,z)}:void 0,v=await
|
|
151
|
+
`)||void 0,Ms={channel:p,chatId:m,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:P,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:I||ps(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:I?void 0:T||void 0,procedureContext:Nt,references:Ft,skillInjection:D||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ht??G,memoryContext:C||void 0,crossChatContext:Lt||void 0,longMemoryRecall:jt||void 0,wikiContext:O,handoverNote:this.buildHandoverNote(e.agentId,p,m),rotationMemo:ws,intent:$?{path:$.path,pathLabel:$.pathLabel,pathId:$.pathId,axes:$.axes,leaf:$.leaf,status:$.status}:void 0,message:e.message},it=Bn(Ms,I?{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),at=(it?.length??0)+(ot?.length??0)+(e.message?.length??0),Ee={history:it?.length??0,sysPrompt:ot?.length??0,message:e.message?.length??0},Bt=cs(e.agentId,p,m);ds(Bt,at,Ee);let qt=us(Bt);qt&&this.log(`[${e.agentId}] ${qt}`),at>16e3&&this.log(`[${e.agentId}] large context for ${p}:${m}: ${at} bytes (history=${Ee.history}, sysPrompt=${Ee.sysPrompt}, message=${Ee.message})`);let ct,Gt=Qt(i.def.tier,this.config.decisions.routing);if(!e.model&&Gt)try{let{routeTaskModel:h}=await import("./routing-ILERJXB6.js"),f=await h({message:e.message,agent:e.agentId,channel:p,isFollowUp:!!A,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,p,m),cheapModel:Gt});f.downgraded&&(ct=f.model,this.log(`[${e.agentId}] ${f.reason}`))}catch{}let Rs={...e,systemPromptAppend:ot,...ct?{model:ct}:{}},Z;try{if(R&&this.workflowAutoRunner)try{let F=await this.workflowAutoRunner({workflowId:R.workflowId,agentId:e.agentId,channel:p,chatId:m,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:p,chatId:m,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:$?.path,matchedWorkflowId:R.workflowId,matchConfidence:R.confidence}});return this.log(`[${e.agentId}] workflow auto-run started ${R.workflowId} run=${F.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),Z={content:"",duration:0,metadata:{handledByWorkflow:R.workflowId,workflowRunId:F.runId,workflowMatchConfidence:R.confidence}},Z}catch(F){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${F?.message||F}`)}if(i.def.tier==="claude-code"){let F=i.def.persistentProcess?Ke():null,z=F!=null&&F.hasLive({agentId:e.agentId,channel:p,chatId:m}),ne=!!A||z,V=[es(ne),is(ne)].find(we=>we&&we.abort);if(V){i.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${V.reason}`);let we={content:"",error:V.message,duration:0};if(!t){g.buffer=`[error] ${V.message}`;for(let Ps of g.subscribers)try{Ps(g.buffer)}catch{}}return Z=we,we}rs();let xe=as();xe&&this.log(`[${e.agentId}] ${xe}`)}let h=i.def.tier==="claude-code",f=h?t:(F,z)=>{F&&y(F),t&&t(F,z)},M=!1,N=h?n:F=>{F&&(M?y(F):(y(`\u{1F4AD} ${F}`),M=!0)),n&&n(F)},U=()=>{M&&(y(`
|
|
152
|
+
`),M=!1)},X=h?f:f?(F,z)=>{U(),f(F,z)}:void 0,v=await Pn(i.def,Rs,this.providers,X,it,A,w,l.signal,N);if(!v.error){let F=To(i.def.toolUseRequired,x);if(F){let z=Array.from(x.entries()).map(([ne,Ne])=>`${ne}=${Ne}`).join(", ")||"none";v.error=`tool_required_not_called: ${F} (invoked: ${z})`,v.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${F}, observed ${z}`)}}Z=v;let Q=v.usage?Wn(v.usage):void 0;if(ee().emit("task:completed",{taskId:b,agentId:e.agentId,channel:p,chatId:m,durationMs:Date.now()-S,error:v.error||void 0,inputTokens:Q?.inputTokens,outputTokens:Q?.outputTokens,cacheReadTokens:Q?.cacheReadTokens,cacheCreateTokens:Q?.cacheCreateTokens,tier2InputTokens:Q?.tier2InputTokens,tier2OutputTokens:Q?.tier2OutputTokens,tier2CacheReadTokens:Q?.tier2CacheReadTokens,tier2CacheCreateTokens:Q?.tier2CacheCreateTokens,finalResponse:v.content||void 0,billedModel:v.billedModel||i.def.model||void 0,at:new Date().toISOString()}),!t&&(v.content||v.error)){let F=v.error?`[error] ${v.error}`:v.content;g.buffer=F;for(let z of g.subscribers)try{z(F)}catch{}}if(v.error)i.errors++,this.log(`[${e.agentId}] error: ${v.error}`);else{if(this.sessions.addAgentMessage(e.agentId,p,m,v.content),v.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,p,m,v.claudeSessionId),v.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,p,m,v.codexSessionId),v.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,p,m,v.opencodeSessionId),(v.claudeSessionId||v.codexSessionId||v.opencodeSessionId)&&v.usage&&this.sessions.recordTurnUsage(e.agentId,p,m,v.usage,v.contextTokens),v.usage){let V=v.contextTokens,xe=(v.usage.inputTokens||0)+(v.usage.cacheReadTokens||0)+(v.usage.cacheCreateTokens||0);(V??xe)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${p}:${m}: context=${V??"n/a"} tokens (cumulative turn total=${xe}) \u2014 next turn will rotate`)}if(Fn({channel:p,content:`User: ${e.message}`,responseLength:v.content.length}).capture){try{let V=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:V,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:p,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
153
153
|
|
|
154
|
-
Agent: ${v.content}`,meta:
|
|
154
|
+
Agent: ${v.content}`,meta:xo($,e.context)})}catch{}Xt(e.agentId,e.message,v.content,{channel:p,chatId:m,sender:P},this.memoryStore).catch(()=>{}),Xn(e.agentId,e.message,v.content,{channel:p,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=v.billedModel||e.model||i.def.model,ne=e.context?.channel,Ne=ne&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ne}:${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,z,ne,Ne),this.log(`[${e.agentId}] completed in ${v.duration}ms`+(v.tokensUsed?` (${v.tokensUsed} tokens)`:""))}return v}catch(h){i.errors++,this.log(`[${e.agentId}] unexpected error: ${h.message}`);let f=Ue(h.message);return Z={content:"",error:We(f),errorKind:f.kind},Z}finally{i.activeTasks--;let h=i.runningTasks.findIndex(f=>f.id===u.id);h!==-1&&i.runningTasks.splice(h,1),this.taskAborts.delete(u.id),g.done=!0,g.endedAt=new Date;for(let f of g.subscribers)try{f(`
|
|
155
155
|
[task finished]
|
|
156
|
-
`)}catch{}g.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(u.id),
|
|
157
|
-
//# sourceMappingURL=chunk-
|
|
156
|
+
`)}catch{}g.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(u.id),yo).unref?.();try{let f=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:f.toISOString(),durationMs:f.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 U=N.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:U,at:f,ok:M.ok})}}catch(f){this.log(`[${e.agentId}] task history persist failed: ${f?.message}`)}this.messageQueue.markDone(e.agentId,a,c).then(f=>{if(f.length!==0){this.log(`[${e.agentId}] flushing ${f.length} queued message(s)`);for(let M of f){let N=M.originalContext||{channel:M.channel,sender:M.sender,chatId:M.chatId};this.execute({message:M.text,agentId:e.agentId,context:N}).then(U=>this.postQueuedResponseToChannel(e.agentId,N,U)).catch(U=>{this.log(`[${e.agentId}] queued message failed: ${U.message}`)})}}}).catch(f=>{this.log(`[${e.agentId}] queue flush failed: ${f.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=j(process.cwd(),be,this.safe(e.agentId),t);Y(n)||fo(n,{recursive:!0});let s=j(n,`${this.safe(e.id)}.json`);ho(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=j(process.cwd(),be,this.safe(e));if(!Y(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=j(a,l);if(Y(g))try{for(let y of te(g)){if(!y.endsWith(".json"))continue;let b=y.split("-")[0],x=parseInt(b,10);if(!Number.isFinite(x)||x<i||x>n)continue;let w=Math.floor((n-x)/36e5),p=t-1-w;p>=0&&p<t&&o[p]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=j(process.cwd(),be);if(!Y(e))return 0;let t=0;for(let n of te(e)){let s=j(e,n),o;try{o=te(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=j(s,i),c;try{c=te(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(Re(j(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=bo){let t=j(process.cwd(),be);if(!Y(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=0;for(let o of te(t)){let i=j(t,o),a;try{a=te(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{mo(j(i,c),{recursive:!0,force:!0}),s++}catch{}}}return s}listTaskHistory(e,t=50){let n=j(process.cwd(),be,this.safe(e));if(!Y(n))return[];let s=te(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=j(n,i),c;try{c=te(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(j(a,d),"utf-8")),{transcript:l,responseText:g,...y}=u;o.push(y)}catch{}}}return o}getTaskRecord(e,t){let n=j(process.cwd(),be,this.safe(e));if(!Y(n))return null;let s=this.safe(t),o=te(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=j(n,i,`${s}.json`);if(Y(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=dn();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),y=!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}`),y=!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:y,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{vo as a,yn as b,Us as c,Bs as d,zs as e,Qs as f,Ys as g,Pn as h,Je as i,ze as j,Xe as k,ee as l,Zn as m,Lr as n,Vn as o,Me as p,co as q,uo as r,lo as s,go as t,po as u,_t as v,Ca as w,va as x,xo as y,wo as z,Et as A,ms as B,hs as C,To as D,ys as E,bs as F};
|
|
157
|
+
//# sourceMappingURL=chunk-ULLAE6LE.js.map
|