agentix-cli 0.141.0 → 0.141.1

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.
@@ -1,2 +1,2 @@
1
- import{A as a,B as b,C as c}from"./chunk-S5DS2V3X.js";import"./chunk-SFQUP3BP.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-QIJLFPWE.js";export{a as createAgentContext,b as generate,c as generateStream};
2
- //# sourceMappingURL=agent-DHCLFYIQ.js.map
1
+ import{A as a,B as b,C as c}from"./chunk-LR4FYHWS.js";import"./chunk-SFQUP3BP.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-QIJLFPWE.js";export{a as createAgentContext,b as generate,c as generateStream};
2
+ //# sourceMappingURL=agent-FXOQO5L7.js.map
@@ -31,14 +31,14 @@ ${n}`}function Md(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
31
31
  `,l)}};N.stdout?.on("data",T=>{O+=F.write(T);let x=O.split(`
32
32
  `);O=x.pop()||"";for(let L of x)Q(L)}),N.stderr?.on("data",T=>{W+=G.write(T)});let $=await N;if(i&&i.removeEventListener("abort",U),O+=F.end(),O.trim()&&Q(O),W+=G.end(),R)return{content:"",error:E||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if($.exitCode!==0||p){let T=$,x;return T.timedOut?x=`OpenCode timed out after ${Math.round(M/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:p?x=p:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+W)?x=mo():x=W.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...Z(x),duration:Date.now()-c,usage:f,opencodeSessionId:h}}return S=!1,{content:l.trim(),duration:Date.now()-c,usage:f,billedModel:e.model||n.model,opencodeSessionId:h}}catch(M){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let P=/ENOENT|spawn opencode/i.test(M?.message||"")?mo():M?.message;return{content:l,...Z(P||"OpenCode failed"),duration:Date.now()-c,usage:f,opencodeSessionId:h}}finally{w?.(),b?.release(S)}}async function Hd(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Se(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function jd(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,f=!1,h=()=>{let S=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(S))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let p=setTimeout(()=>{f=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);p.unref?.();let b=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let S=n.provider||"claude-code",w=s?`${s}
33
33
 
34
- ${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),N=e.context?.channel==="web-chat"&&P?{userId:M,agentId:e.agentId||"acme-public"}:void 0,R=Zs(n),E=Object.keys(R).length>0,U={task:w,cwd:n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:N,providerOpts:o,abortSignal:l.signal,mcpServers:E?R:void 0};if(r){let{generateStream:Q}=await import("./agent-DHCLFYIQ.js"),$="",T,x,L,j;for await(let C of Q(U)){if(c)try{c(C)}catch{}if(C.type==="text_delta")$+=C.text,r(C.text,$);else if(C.type==="thinking_delta")C.text&&i&&i(C.text);else if(C.type==="generate_result"){if(C.result.content&&C.result.content!==$){let q=C.result.content.slice($.length);q?($=C.result.content,r(q,$)):$=C.result.content}T=C.result.tokensUsed,C.result.inputTokens!=null&&(x=C.result.inputTokens),C.result.outputTokens!=null&&(L=C.result.outputTokens)}else if(C.type==="done"){if(C.result.content&&C.result.content!==$){let q=C.result.content.slice($.length);q?($=C.result.content,r(q,$)):$=C.result.content}C.result.tokensUsed!=null&&(T=C.result.tokensUsed)}else C.type==="error"&&(j=C.error)}return j&&!$?f?b():j==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${j}`),duration:Date.now()-d}:((x===void 0||L===void 0)&&T&&(x=Math.round(T*.7),L=T-x),{content:$||"Done.",tokensUsed:T,usage:x!==void 0||L!==void 0?{inputTokens:x||0,outputTokens:L||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:O}=await import("./agent-DHCLFYIQ.js"),W=await O(U),F=W.inputTokens,G=W.outputTokens;if((F===void 0||G===void 0)&&W.tokensUsed){let Q=W.tokensUsed;F=Math.round(Q*.7),G=Q-F}return{content:W.content||"Done.",tokensUsed:W.tokensUsed,usage:F!==void 0||G!==void 0?{inputTokens:F||0,outputTokens:G||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(S){return f?b():S?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${S.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var vn=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},Bd=1e3;async function Wd(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),Bd),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function qd(n,e,t,s,r,o,i){let a=Et();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Ht(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let f,h=!1;try{let $=a.list().length;f=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>$}catch($){return $ instanceof Ne,null}h&&Mn(e.agentId,n,e.model,s,"persistent");let p=Se(n,e,t),b="",S,w,M,P,N,R,E,U="",O="",W=$=>{if(!i||!$)return;let T;if(O&&$.startsWith(O)?T=$.slice(O.length):T=U&&!U.endsWith(`
34
+ ${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),N=e.context?.channel==="web-chat"&&P?{userId:M,agentId:e.agentId||"acme-public"}:void 0,R=Zs(n),E=Object.keys(R).length>0,U={task:w,cwd:n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:N,providerOpts:o,abortSignal:l.signal,mcpServers:E?R:void 0};if(r){let{generateStream:Q}=await import("./agent-FXOQO5L7.js"),$="",T,x,L,j;for await(let C of Q(U)){if(c)try{c(C)}catch{}if(C.type==="text_delta")$+=C.text,r(C.text,$);else if(C.type==="thinking_delta")C.text&&i&&i(C.text);else if(C.type==="generate_result"){if(C.result.content&&C.result.content!==$){let q=C.result.content.slice($.length);q?($=C.result.content,r(q,$)):$=C.result.content}T=C.result.tokensUsed,C.result.inputTokens!=null&&(x=C.result.inputTokens),C.result.outputTokens!=null&&(L=C.result.outputTokens)}else if(C.type==="done"){if(C.result.content&&C.result.content!==$){let q=C.result.content.slice($.length);q?($=C.result.content,r(q,$)):$=C.result.content}C.result.tokensUsed!=null&&(T=C.result.tokensUsed)}else C.type==="error"&&(j=C.error)}return j&&!$?f?b():j==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${j}`),duration:Date.now()-d}:((x===void 0||L===void 0)&&T&&(x=Math.round(T*.7),L=T-x),{content:$||"Done.",tokensUsed:T,usage:x!==void 0||L!==void 0?{inputTokens:x||0,outputTokens:L||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:O}=await import("./agent-FXOQO5L7.js"),W=await O(U),F=W.inputTokens,G=W.outputTokens;if((F===void 0||G===void 0)&&W.tokensUsed){let Q=W.tokensUsed;F=Math.round(Q*.7),G=Q-F}return{content:W.content||"Done.",tokensUsed:W.tokensUsed,usage:F!==void 0||G!==void 0?{inputTokens:F||0,outputTokens:G||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(S){return f?b():S?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${S.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var vn=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},Bd=1e3;async function Wd(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),Bd),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function qd(n,e,t,s,r,o,i){let a=Et();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Ht(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let f,h=!1;try{let $=a.list().length;f=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>$}catch($){return $ instanceof Ne,null}h&&Mn(e.agentId,n,e.model,s,"persistent");let p=Se(n,e,t),b="",S,w,M,P,N,R,E,U="",O="",W=$=>{if(!i||!$)return;let T;if(O&&$.startsWith(O)?T=$.slice(O.length):T=U&&!U.endsWith(`
35
35
  `)?`
36
36
 
37
37
  ${$}`:$,O=$,!!T){U+=T;try{i(T,U)}catch{}}},F=!1,G=()=>{F=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?G():o.addEventListener("abort",G,{once:!0}));let Q=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of f.runTurn({message:p,taskId:e.taskId??"unknown",deadlineMs:$})){if(Q=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let x=T.raw.message?.content??[];for(let j of x)j.type==="text"&&typeof j.text=="string"?(b=j.text,W(j.text)):j.type==="tool_use"&&(O="");let L=T.raw.message?.usage;if(L){let j=(L.input_tokens||0)+(L.cache_read_input_tokens||0)+(L.cache_creation_input_tokens||0);j>0&&(P=j)}}if(T.type==="result"){let x=T.raw;if(x.is_error){let L=Z(typeof x.result=="string"?x.result:"claude error");S=L.error,w=L.errorKind}else typeof x.result=="string"&&x.result.length>0&&(b=x.result,U||W(x.result));typeof x.session_id=="string"&&(E=x.session_id),x.usage&&(M={inputTokens:x.usage.input_tokens||0,outputTokens:x.usage.output_tokens||0,cacheReadTokens:x.usage.cache_read_input_tokens||0,cacheCreateTokens:x.usage.cache_creation_input_tokens||0}),typeof x.num_turns=="number"&&(N=x.num_turns),typeof x.message?.model=="string"?R=x.message.model:typeof x.model=="string"?R=x.model:R=_t(x.modelUsage)||R}}}catch($){if(F)S="task cancelled by operator",w="cancelled";else if(Q)if($ instanceof Ve)S=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,w="interrupted";else if($ instanceof Ze){let T=Z(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);S=T.error,w=T.errorKind}else{let T=Z(`persistent claude process error: ${$?.message||String($)}`);S=T.error,w=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${$?.message||$}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",G),null}finally{o&&o.removeEventListener("abort",G)}return F&&!S&&(S="task cancelled by operator",w="cancelled"),{content:F?"":b,error:S,errorKind:w,duration:Date.now()-c,usage:M,contextTokens:P,numTurns:N,billedModel:R,claudeSessionId:E}}function Po(n){let e=ge(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?ao(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:po(t.args,n.taskId,n.agentId)}function Gd(n){return ge(n.autonomy)||!!n.personLimits}async function Kd(n,e,t,s,r,o,i){let a=ge(e.autonomy)?e.autonomy:void 0,c=a&&co(a,n.tier)||e.personLimits&&fo(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${Ds(a)}
38
38
 
39
39
  ${e.message}`:e.message},l=[a?`level=${a}`:"",e.personLimits?`person=${e.personLimits.personId}`:""].filter(Boolean).join(" ");process.stderr.write(`[claude-guarded] agent=${e.agentId} ${l} task=${d} via=spawn (persistent process bypassed)
40
40
  `),e.personLimits&&lo(d,e.personLimits);try{let f=t?await Ro(n,u,t,s,r,o,i):await Mo(n,u,s,r,i);if(!a)return f;let h=uo(d);return{...f,autonomy:a,...h.length?{autonomyBlocks:h}:{}}}finally{e.personLimits&&go(d)}}async function _o(n,e,t,s,r,o,i,a,c){if(Gd(e))return Kd(n,e,s,r,o,i,a);switch(n.tier){case"claude-code":if(n.persistentProcess){let d=await qd(n,e,r,o,i,a,s);if(d!==null)return d}return s?Ro(n,e,s,r,o,i,a):Mo(n,e,r,o,a);case"codex-cli":if(n.persistentProcess)try{let d=await Vr.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:n.workspace,env:Ft(n,e),args:ko(),model:e.model||n.model,bypass:n.permissionMode==="bypassPermissions",prompt:$n(Se(n,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:s});return{...d,...d.error?Z(d.error):{}}}catch(d){if(!(d instanceof be))throw d;if(i?.({type:"codex.fallback",reason:d.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return s?Ud(n,e,s,r,o,i):Ld(n,e,r,o);case"opencode":return Fd(n,e,s,r,o,i,a,c);case"sdk":{let d=n.provider||"claude",u=t[d]?.apiKey;return u?Hd(n,e,u,r):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=n.provider||"claude-code",u=t[d],l=u?.apiKey;return jd(n,e,l,r,s,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${n.tier}`}}}import{readFileSync as Ue,writeFileSync as Eo,mkdirSync as Jd,existsSync as Rn,readdirSync as Pn}from"fs";import{resolve as Fe}from"path";var _n=12e3,st=30,zd=720,Qd=40,Xd=18e4,Yd="[Compacted conversation summary",Zd=7*864e5,Vd=[/\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 ec(n){return n?Vd.some(e=>e.test(n)):!1}var tc=[{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 Oo(n){if(!n)return null;let e=0;for(let t of tc)t.re.test(n)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Do(n,e,t,s){if(n.length===0)return!1;let r=n[n.length-1];return r.role===e&&(r.name??"")===t&&r.content===s}function No(n,e){let t=(n??[]).filter(o=>o.role==="user"),s=t[t.length-1];return s?(s.content===e?t[t.length-2]:s)?.content??null:null}function Lo(n,e,t){if(t<=0)return[];let s=(n??[]).filter(i=>i.role==="user"),r=s[s.length-1],o=(r&&r.content===e?s.length-1:s.length)-1;return o<=0?[]:s.slice(Math.max(0,o-t),o).map(i=>i.content)}function nc(n){let e=n.slice(11,16),t=e.slice(0,2),s=parseInt(e.slice(3,5),10);if(Number.isNaN(s))return e;let r=Math.floor(s/15)*15;return`${t}:${r.toString().padStart(2,"0")}`}var jt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;tierTwoThresholdTokensByChannel;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Fe(e,".agentx/sessions"),Rn(this.sessionsDir)||Jd(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??zd),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??Qd),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Xd),this.tierTwoThresholdTokensByChannel=Object.fromEntries(Object.entries(t.tierTwoThresholdTokensByChannel??{}).map(([s,r])=>[s,Math.max(5e4,r)]))}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,s,r){if(r?.length){let u=this.getSession(e,t,s);u.messages.length===0&&this.appendSeededMessages(u,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,s),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,s);if(a.messages.length>0)return;let c=this.adapterResolver(t);if(!c?.seedHistory)return;let d=(async()=>{try{let u=await c.seedHistory(s,{maxMessages:st,maxChars:_n});u.length>0&&this.appendSeededMessages(a,u)}catch{}})();this.seedingPromises.set(o,d);try{await d}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let s=new Set;for(let o of e.messages)o.externalId&&s.add(o.externalId);let r=0;for(let o of t)o.externalId&&s.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.externalId}),r++);r!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,s){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${s}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Fe(this.sessionsDir,`${t}.json`)}getSession(e,t,s){let r=this.sessionKey(e,t,s);if(this.cache.has(r))return this.cache.get(r);let o=this.sessionFile(r);if(Rn(o))try{let d=JSON.parse(Ue(o,"utf-8"));return this.cache.set(r,d),d}catch{}let i=this.loadPreviousDaySession(e,t,s),a=new Date().toISOString().slice(0,10),c={id:r,agentId:e,channel:t,chatId:s,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(r,c),this.save(c),c}loadPreviousDaySession(e,t,s){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${s}:${r}`,i=this.sessionFile(o);if(!Rn(i))return null;try{return JSON.parse(Ue(i,"utf-8"))}catch{return null}}addUserMessage(e,t,s,r,o){let i=this.getSession(e,t,s);Do(i.messages,"user",r,o)||(i.messages.push({role:"user",name:r,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,s,r){let o=this.getSession(e,t,s),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(r||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,s,r){let o=this.getSession(e,t,s);Do(o.messages,"agent",e,r)||(o.messages.push({role:"agent",name:e,content:r,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,s){return this.getSession(e,t,s).claudeSessionId}setClaudeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.claudeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getCodexSessionId(e,t,s){return this.getSession(e,t,s).codexSessionId}setCodexSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.codexSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,s){return this.getSession(e,t,s).opencodeSessionId}setOpenCodeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.opencodeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,s,r={}){let o=this.getSession(e,t,s);if(o.messages.length===0)return"";let i=Math.max(1,r.maxMessages??st),a=Math.max(200,r.maxChars??_n),c=[],d=0;for(let f=o.messages.length-1;f>=0&&c.length<i;f--){let h=o.messages[f];if(d+=h.content.length,c.push(h),d>=a)break}c.reverse();let u=[`[Conversation history for today (${o.day})]`],l="";for(let f of c){let h=nc(f.timestamp);h!==l&&(u.push(`\u2014 ${h} \u2014`),l=h);let p=f.name||(f.role==="user"?"User":"Agent");u.push(`${p}: ${f.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
41
- `)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),s=new Date;s.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():s.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=Pn(this.sessionsDir).filter(N=>N.startsWith(`${a}:`)&&N.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$/,f=c.filter(N=>{let R=N.match(l);if(!R)return!1;let E=R[1];return E>=d&&E<=u}),h=[],p=0,b=e.query?.toLowerCase(),S=e.participants?.length?new Set(e.participants):void 0;for(let N of f){let R;try{R=JSON.parse(Ue(Fe(this.sessionsDir,N),"utf-8"))}catch{continue}if(R.agentId===e.agentId&&!(e.channel&&R.channel!==e.channel)&&!(e.chatId&&R.chatId!==e.chatId))for(let E of R.messages)p++,!(!E.timestamp||E.timestamp<o||E.timestamp>=i)&&(S&&E.role==="user"&&!S.has(E.name??"")||b&&!E.content.toLowerCase().includes(b)||h.push({ts:E.timestamp,role:E.role,senderName:E.name??"",content:E.content,channel:R.channel,chatId:R.chatId,day:R.day,sessionFile:N}))}h.sort((N,R)=>R.ts.localeCompare(N.ts));let w=h.slice(0,t),M=w.length>0?w[w.length-1].ts:null,P=h.length>t;return{turns:w,oldestTs:M,hasMore:P,totalScanned:p}}recentByChatId(e){let t=Math.min(Math.max(e.limit??st,1),200),s=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=s.slice(0,10),o;try{o=Pn(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 f=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return f?f[1]>=r:!1}),c=[];for(let l of a){let f;try{f=JSON.parse(Ue(Fe(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(f.channel!==e.channel||f.chatId!==e.chatId))for(let h of f.messages)!h.timestamp||h.timestamp<s||c.push({ts:h.timestamp,role:h.role,senderName:h.name??"",content:h.content,agentId:f.agentId,sessionFile:l})}let d=new Set,u=[];for(let l of c){let f=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;d.has(f)||(d.add(f),u.push(l))}return u.sort((l,f)=>l.ts.localeCompare(f.ts)),u.slice(-t)}sessionIdleMs(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,s,r){let o=this.getSession(e,t,s);return!o.claudeSessionId&&!o.codexSessionId&&!o.opencodeSessionId?!1:(r??Date.now()-new Date(o.updatedAt).getTime())>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,s,r){if(r!==void 0&&r!==""&&!ec(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,s);try{let a=Pn(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(Ue(Fe(this.sessionsDir,d),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),h=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,p=l.map(b=>` [${b.timestamp.slice(11,16)}] ${b.name||b.role}: ${b.content.slice(0,200)}`);c.push(`From ${h} (${u.channel}):
41
+ `)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),s=new Date;s.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():s.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=Pn(this.sessionsDir).filter(N=>N.startsWith(`${a}:`)&&N.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$/,f=c.filter(N=>{let R=N.match(l);if(!R)return!1;let E=R[1];return E>=d&&E<=u}),h=[],p=0,b=e.query?.toLowerCase(),S=e.participants?.length?new Set(e.participants):void 0;for(let N of f){let R;try{R=JSON.parse(Ue(Fe(this.sessionsDir,N),"utf-8"))}catch{continue}if(R.agentId===e.agentId&&!(e.channel&&R.channel!==e.channel)&&!(e.chatId&&R.chatId!==e.chatId))for(let E of R.messages)p++,!(!E.timestamp||E.timestamp<o||E.timestamp>=i)&&(S&&E.role==="user"&&!S.has(E.name??"")||b&&!E.content.toLowerCase().includes(b)||h.push({ts:E.timestamp,role:E.role,senderName:E.name??"",content:E.content,channel:R.channel,chatId:R.chatId,day:R.day,sessionFile:N}))}h.sort((N,R)=>R.ts.localeCompare(N.ts));let w=h.slice(0,t),M=w.length>0?w[w.length-1].ts:null,P=h.length>t;return{turns:w,oldestTs:M,hasMore:P,totalScanned:p}}recentByChatId(e){let t=Math.min(Math.max(e.limit??st,1),200),s=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=s.slice(0,10),o;try{o=Pn(this.sessionsDir).filter(l=>l.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`.replace(/[^a-zA-Z0-9_:-]/g,"_"),a=o.filter(l=>{if(!l.includes(i))return!1;let f=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return f?f[1]>=r:!1}),c=[];for(let l of a){let f;try{f=JSON.parse(Ue(Fe(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(f.channel!==e.channel||f.chatId!==e.chatId))for(let h of f.messages)!h.timestamp||h.timestamp<s||c.push({ts:h.timestamp,role:h.role,senderName:h.name??"",content:h.content,agentId:f.agentId,sessionFile:l})}let d=new Set,u=[];for(let l of c){let f=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;d.has(f)||(d.add(f),u.push(l))}return u.sort((l,f)=>l.ts.localeCompare(f.ts)),u.slice(-t)}sessionIdleMs(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,s,r){let o=this.getSession(e,t,s);return!o.claudeSessionId&&!o.codexSessionId&&!o.opencodeSessionId?!1:(r??Date.now()-new Date(o.updatedAt).getTime())>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,s,r){if(r!==void 0&&r!==""&&!ec(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,s);try{let a=Pn(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(Ue(Fe(this.sessionsDir,d),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),h=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,p=l.map(b=>` [${b.timestamp.slice(11,16)}] ${b.name||b.role}: ${b.content.slice(0,200)}`);c.push(`From ${h} (${u.channel}):
42
42
  ${p.join(`
43
43
  `)}`)}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(`
44
44
  `)}catch{return""}}async compactIfNeeded(e,t,s,r){let o=this.getSession(e,t,s),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-FS6XNRLM.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,r,{channel:t,chatId: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,s){let r=this.getSession(e,t,s);return r.messages.length>0&&r.messages[0].content.startsWith(Yd)}clearClaudeSessionId(e,t,s){let r=this.getSession(e,t,s);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,s){let r=this.getSession(e,t,s);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.getTierTwoThresholdTokens(t)}recordTurnUsage(e,t,s,r,o){let i=this.getSession(e,t,s);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.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(Ue(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,s,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${s}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},Eo(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,s){let r=this.readRotationMemos()[`${e}:${t}:${s}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>Zd?null:r}getTurnCount(e,t,s){return this.getSession(e,t,s).turnCount??0}getLastTurnInputTokens(e,t,s){return this.getSession(e,t,s).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,s){let r=this.getSession(e,t,s);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getRawLastTurnContextTokens(e,t,s){return this.getSession(e,t,s).lastTurnContextTokens??null}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(e){return(e?this.tierTwoThresholdTokensByChannel[e]:void 0)??this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>st&&(e.messages=e.messages.slice(-st));let s=e.messages.reduce((o,i)=>o+i.content.length,0);for(;s>_n&&e.messages.length>2;){let o=e.messages.shift();s-=o.content.length}let r=t-e.messages.length;r>0&&Ae.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${s}c)`)}save(e){try{let t=this.sessionFile(e.id);Eo(t,JSON.stringify(e,null,2))}catch{}}};var Bt=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),s=this.windows.get(e)||[],r=t-36e5,o=s.filter(c=>c>r),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 s=t.maxWaitMs??3e5,r=Date.now()+s,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(s/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,c))}}usage(e){let t=Date.now(),s=this.windows.get(e)||[];return{lastMinute:s.filter(r=>r>t-6e4).length,lastHour:s.filter(r=>r>t-36e5).length}}};var sc={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,"workflow-run":200,memory:400,history:1200,"cross-chat":800,wiki:2500}},Uo=4;function Fo(n,e=sc){let t=rc(n,e);t.sort((i,a)=>i.priority-a.priority);let s=[],r=0,o=e.totalBudget*Uo;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Uo,c=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(r+c.length>o){let d=o-r;d>100&&s.push(c.slice(0,d)+"...");break}s.push(c),r+=c.length}return s.join(`
@@ -171,4 +171,4 @@ ${$e}`),m+=$e.length}catch{}}}let Ga=sn.length>0?sn.join(`
171
171
 
172
172
  Agent: ${A.content}`,meta:eg(ee,e.context)})}catch{}tr(e.agentId,e.message,A.content,{channel:y,chatId:I,sender:en},this.memoryStore).catch(()=>{}),Ko(e.agentId,e.message,A.content,{channel:y,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=A.billedModel||e.model||d.def.model,ye=e.context?.channel,It=ye&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ye}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,A.duration||0,A.usage,e.message.length,A.content.length,!1,z,ye,It),this.log(`[${e.agentId}] completed in ${A.duration}ms`+(A.tokensUsed?` (${A.tokensUsed} tokens)`:"")+` ${L()}`)}return A}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=Rt(g.message);return re={content:"",error:Pt(m),errorKind:m.kind},re}finally{if(Cs.stop(),Ms&&ae&&ke)try{let g=re?.usage,m=Pr(ke,ae,{error:re?re.error||void 0:S.signal.aborted?_e(S.signal).message:"run ended before completion",canceled:_r(re?.errorKind)||this.stoppedRuns.has(p.id)||this.interruptedRuns.has(p.id)||!re&&S.signal.aborted,durationMs:Date.now()-p.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:an,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});m&&m!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${m.status} (${m.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${g?.message||g}`)}se(re),es(re)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);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:this.withWorkflowSteps(e.runningTasks),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:Er(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=J(process.cwd(),We,this.safe(e.agentId),t);de(s)||Wl(s,{recursive:!0});let r=J(s,`${this.safe(e.id)}.json`);Gl(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=J(process.cwd(),We,this.safe(e));if(!de(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let f=J(a,l);if(de(f))try{for(let h of pe(f)){if(!h.endsWith(".json"))continue;let p=h.split("-")[0],b=parseInt(p,10);if(!Number.isFinite(b)||b<i||b>s)continue;let S=Math.floor((s-b)/36e5),w=t-1-S;w>=0&&w<t&&o[w]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=J(process.cwd(),We);if(!de(e))return 0;let t=0;for(let s of pe(e)){let r=J(e,s),o;try{o=pe(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=J(r,i),c;try{c=pe(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(dt(J(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let f=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:f,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Vl){let t=J(process.cwd(),We);if(!de(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of pe(t)){let i=J(t,o),a;try{a=pe(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{ql(J(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=J(process.cwd(),We,this.safe(e));if(!de(s))return[];let r=pe(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=J(s,i),c;try{c=pe(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(dt(J(a,d),"utf-8")),{transcript:l,responseText:f,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let s=J(process.cwd(),We,this.safe(e));if(!de(s))return null;let r=this.safe(t),o=pe(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=J(s,i,`${r}.json`);if(de(a))try{return JSON.parse(dt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=Sr();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||Xe(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Ht(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let r=[...this.taskAborts].filter(([,o])=>o.agentId===e.agentId&&o.channel===e.channel&&o.chatId===e.chatId).map(([o])=>o);t=r.length===1?r[0]:void 0}let s=t?this.taskAborts.get(t):void 0;return!t||!s?null:{taskId:t,traceId:s.traceId,agentId:s.agentId,channel:s.channel,chatId:s.chatId,sender:s.sender,rootId:s.rootId,originalMessage:s.originalMessage,origin:s.origin??null,...s.workflowRunId?{workflowRunId:s.workflowRunId}:{}}}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){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));let f=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:f,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let h=this.messageQueue.pendingCount(i,a,c);V().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(f).toISOString(),sender:{name:s},humanRoot:!1,person:Ls(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:f});let p=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),p=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${h}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:p,edited:l,pending:h}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=f=>{u||(u=!0,d(f))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:f=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:f,queued:!1})}).then(f=>{Xe(f.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):f.error?l({ok:!1,status:500,error:f.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:f.viaAttachedSession?"attached":"other"})}).catch(f=>l({ok:!1,status:500,error:f?.message??String(f)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function ag(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[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.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
173
173
  `)}export{Vr as a,Ig as b,to as c,pd as d,no as e,Dt as f,Og as g,Fg as h,Hg as i,Gg as j,Ht as k,Dd as l,Mo as m,Fd as n,Hd as o,jd as p,_o as q,jt as r,Bt as s,dc as t,bp as u,xp as v,On as w,V as x,Jo as y,wc as z,Ic as A,Xo as B,Lp as C,Yo as D,ti as E,ai as F,Yp as G,di as H,Gt as I,nf as J,sf as K,it as L,Au as M,Cu as N,Mu as O,Ru as P,Pu as Q,Bn as R,na as S,at as T,sa as U,Hf as V,jf as W,Bf as X,Wf as Y,qf as Z,Gf as _,Kf as $,dl as aa,zl as ba,Ql as ca,uh as da,lh as ea,eg as fa,tg as ga,sg as ha,Vn as ia,Sa as ja,Ia as ka,og as la,Ta as ma,ka as na,ag as oa};
174
- //# sourceMappingURL=chunk-CELYB3UW.js.map
174
+ //# sourceMappingURL=chunk-HIEJXGYD.js.map